PHP: this extension requires PHP 5.4+, version PHP 5.4.4 or never. The required PHP extensions are PCRE (enabled by default), and the memcached extension version 2.0.x.
The mysqlnd_memcache Memcache
plugin supports all PHP applications and all available PHP MySQL extensions
(mysqli,
mysql,
PDO_MYSQL).
The PHP MySQL extension must be configured with
mysqlnd support.
For accessing InnoDB tables, this PHP extension requires
MySQL Server 5.6.6 or newer with the InnoDB Memcache
Daemon Plugin enabled.
For accessing MySQL Cluster NDB tables, this PHP extension requires
MySQL Cluster 7.2 or newer with the NDB Memcache API nodes
enabled.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/mysqlnd_memcache
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| mysqlnd_memcache.enable | 1 | PHP_INI_SYSTEM |
Available since 1.0.0 |
Here's a short explanation of the configuration directives.
mysqlnd_memcache.enable
integer
Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.
Note:
This option is mainly used by developers to build this extension statically into PHP. General users are encouraged to build this extension as a shared object, and to unload it completely when it is not needed.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
MySQL Memcache Plugin related
MYSQLND_MEMCACHE_DEFAULT_REGEXP
(string)
SELECT
statements that will be mapped into a MySQL Memcache Plugin access point, if possible.
It is also possible to use mysqlnd_memcache_set(), but the default
approach is using this regular expression for pattern matching.
Assorted
The version number of this plugin can be obtained by using
MYSQLND_MEMCACHE_VERSION or
MYSQLND_MEMCACHE_VERSION_ID.
MYSQLND_MEMCACHE_VERSION
is the string representation of the numerical version number
MYSQLND_MEMCACHE_VERSION_ID, which is an integer such as 10000.
Developers can calculate the version number as follows.
| Version (part) | Example |
|---|---|
| Major*10000 | 1*10000 = 10000 |
| Minor*100 | 0*100 = 0 |
| Patch | 0 = 0 |
| MYSQLND_MEMCACHE_VERSION_ID | 10000 |
(PECL mysqlnd_memcache >= 1.0.0)
mysqlnd_memcache_get_config — Returns information about the plugin configuration
This function returns an array of all mysqlnd_memcache related configuration information that is attached to the MySQL connection. This includes MySQL, the Memcache object provided via mysqlnd_memcache_set(), and the table mapping configuration that was automatically collected from the MySQL Server.
An array of mysqlnd_memcache configuration information on success, otherwise FALSE.
The returned array has these elements:
| Array Key | Description |
|---|---|
| memcached | Instance of Memcached associated to this MySQL connection by mysqlnd_memcache_set(). You can use this to change settings of the memcache connection, or directly by querying the server on this connection. |
| pattern |
The PCRE regular expression used to match the SQL query sent to the server.
Queries matching this pattern will be further analyzed to decide whether
the query can be intercepted and sent via the memcache interface or
whether the query is sent using the general MySQL protocol to the
server. The pattern is either the default pattern
(MYSQLND_MEMCACHE_DEFAULT_REGEXP) or it is set via
mysqlnd_memcache_set().
|
| mappings | An associative array with a list of all configured containers as they were discovered by this plugin. The key for these elements is the name of the container in the MySQL configuration. The value is described below. The contents of this field is created by querying the MySQL Server during association to MySQL and a memcache connection using mysqlnd_memcache_set(). |
| mapping_query | An SQL query used during mysqlnd_memcache_set() to identify the available containers and mappings. The result of that query is provided in the mappings element. |
| Array Key | Description |
|---|---|
| prefix | A prefix used while accessing data via memcache. With the MySQL InnoDB Memcache Deamon plugin, this usually begins with @@ and ends with a configurable separator. This prefix is placed in front of the key value while using the memcache protocol. |
| schema_name | Name of the schema (database) which contains the table being accessed. |
| table_name | Name of the table which contains the data accessible via memcache protocol. |
| id_field_name | Name of the database field (column) with the id used as key when accessing the table via memcache. Often this is the database field having a primary key. |
| separator |
The separator used to split the different field values. This is needed as
memcache only provides access to a single value while MySQL can map
multiple columns to this value.
|
| fields | An array with the name of all fields available for this mapping. |
Example #1 mysqlnd_memcache_get_config() example
<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc);
var_dump(mysqlnd_memcache_get_config($mysqli));
?>
The above example will output:
array(4) {
["memcached"]=>
object(Memcached)#2 (0) {
}
["pattern"]=>
string(125) "/^\s*SELECT\s*(.+?)\s*FROM\s*`?([a-z0-9_]+)`?\s*WHERE\s*`?([a-z0-9_]+)`?\s*=\s*(?(?=["'])["']([^"']*)["']|([0-9e\.]*))\s*$/is"
["mappings"]=>
array(1) {
["mymem_test"]=>
array(6) {
["prefix"]=>
string(13) "@@mymem_test."
["schema_name"]=>
string(4) "test"
["table_name"]=>
string(10) "mymem_test"
["id_field_name"]=>
string(2) "id"
["separator"]=>
string(1) "|"
["fields"]=>
array(3) {
[0]=>
string(2) "f1"
[1]=>
string(2) "f2"
[2]=>
string(2) "f3"
}
}
}
["mapping_query"]=>
string(209) " SELECT c.name,
CONCAT('@@', c.name, (SELECT value FROM innodb_memcache.config_options WHERE name = 'table_map_delimiter')) AS key_prefix,
c.db_schema,
c.db_table,
c.key_columns,
c.value_columns,
(SELECT value FROM innodb_memcache.config_options WHERE name = 'separator') AS sep
FROM innodb_memcache.containers c"
}
(PECL mysqlnd_memcache >= 1.0.0)
mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection
$mysql_connection
[, Memcached $memcache_connection
[, string $pattern
[, callback $callback
]]] ) : bool
Associate mysql_connection with
memcache_connection using pattern
as a PCRE regular expression, and callback as a notification
callback or to unset the association of mysql_connection.
While associating a MySQL connection with a Memcache connection, this function will query the MySQL Server for its configuration. It will automatically detect whether the server is configured to use the InnoDB Memcache Daemon Plugin or MySQL Cluster NDB Memcache support. It will also query the server to automatically identify exported tables and other configuration options. The results of this automatic configuration can be retrieved using mysqlnd_memcache_get_config().
mysql_connectionA handle to a MySQL Server using one of the MySQL API extensions for PHP, which are PDO_MYSQL, mysqli or ext/mysql.
memcache_connection
A Memcached instance with a
connection to the MySQL Memcache Daemon plugin. If this parameter
is omitted, then mysql_connection will be unassociated
from any memcache connection. And if a previous association exists, then it will be
replaced.
pattern
A regular expression in Perl Compatible
Regular Expression syntax used to identify potential
Memcache-queries. The query should have three sub patterns. The
first subpattern contains the requested field list, the second the name
of the ID column from the query and the third the requested value. If
this parameter is omitted or os set to NULL, then a default
pattern will be used.
callbackA callback which will be used whenever a query is being sent to MySQL. The callback will receive a single boolean parameter telling if a query was sent via Memcache.
TRUE if the association or disassociation is successful, otherwise FALSE if there
is an error.
Example #1 mysqlnd_memcache_set() example with var_dump() as a simple debugging callback.
<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc, NULL, 'var_dump');
/* This query will be intercepted and executed via Memcache protocol */
echo "Sending query for id via Memcache: ";
$mysqli->query("SELECT f1, f2, f3 FROM test WHERE id = 1");
/* f1 is not configured as valid key field, this won't be sent via Memcache */
echo "Sending query for f1 via Memcache: ";
$mysqli->query("SELECT id FROM test WHERE f1 = 1");
mysqlnd_memcache_set($mysqli);
/* Now the regular MySQL protocol will be used */
echo "var_dump won't be invoked: ";
$mysqli->query("SELECT f1, f2, f3 WHERE id = 1");
?>
The above example will output:
Sending query for id via Memcache: bool(true) Sending query for f1 via Memcache: bool(false) var_dump won't be invoked:
This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.
See also the CHANGES file in the source distribution for a complete list of changes.
1.0.0-alpha
The initial release does map basic SQL SELECT statements to a MySQL Memcache plugin access. This bares potential performance benefits as the direct key-value access to MySQL storage using the Memcache protocol is usually faster than using SQL access.
These functions allow you to access Oracle Database 19c, 18c, 12c, 11g, 10g, 9i and 8i. They support SQL and PL/SQL statements. Basic features include transaction control, binding of PHP variables to Oracle placeholders, and support for large object (LOB) types and collections. Oracle's scalability features such as Database Resident Connection Pooling (DRCP) and result caching are also supported.
The OCI8 1.4 extension is included with PHP 5.3, PHP 5.4 and PHP 5.5. It is also available from » PECL. A newer OCI8 2.0 version is available only from » PECL. OCI8 1.4 requires Oracle 12c, 11g, 10g or 9iR2 client libraries and will install on PHP 4.3.9 onwards. OCI8 2.0 requires Oracle 12c, 11g or 10g client libraries and will install on PHP 5.2 onwards.
If the Oracle Database is on the same machine as PHP, the database software already contains the necessary libraries. When PHP is on a different machine, use the free » Oracle Instant Client libraries.
To use Oracle Instant Client, install the basic
or basiclite Oracle Instant Client ZIP file or
RPM package. When building PHP from source code, also install
the sdk ZIP file or devel RPM
package.
You must run PHP with the same, or a more recent, version of the Oracle libraries that OCI8 was built with.
On Windows, the php_oci8 DLL needs Oracle client libraries from version 10gR2 or greater. In PHP 5.3 up to and including PHP 5.3.5, the php_oci8_11g DLL requires Oracle 11gR1 or greater client libraries. From PHP 5.3.6 the php_oci8_11g DLL requires Oracle 11gR2 or greater client libraries. The php_oci8_12c DLL from PECL requires Oracle 12cR1 client libraries. With some versions of Instant Client you may additionally need mfc71.dll and msvcr71.dll libraries.
Note:
If OCI8 uses 9iR2 client libraries, then PHP can connect to Oracle Database 8i, 9iR2, 10g or 11g. If OCI8 uses 10gR2 client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 11g client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 12c client libraries, the database can be 10gR2, 11g or 12c.
Note:
Full OCI8 feature support is only available when using the most recent versions of the Oracle client libraries and database.
Review the previous Requirements section before configuring OCI8.
To enable the OCI8 extension, configure PHP with the option --with-oci8.
Before starting the web server, OCI8 typically requires several Oracle environment variables (see below) to locate libraries, point to configuration files, and set some basic properties such as the character set used by Oracle libraries. The variables must be set before any PHP process starts.
The PHP binary must link with the same, or more recent, major version of Oracle libraries as it was configured with. For example, if you build OCI8 with Oracle 11.2 libraries, then PHP should also be deployed and run with Oracle 11.2 libraries. PHP applications can connect to other versions of Oracle Database, since Oracle has client-server cross-version compatibility.
The configuration shared option
builds OCI8 as a shared library that can be dynamically loaded into
PHP. Building a shared extension allows OCI8 to be upgraded easily
without impacting the rest of PHP.
Configure OCI8 using one of the following configure options.
If using the free » Oracle Instant Client libraries, then do:
./configure --with-oci8=shared,instantclient,/path/to/instant/client/lib
If Instant Client is installed from ZIP files, make sure to create
the library symbolic link first, for example ln -s
libclntsh.so.12.1 libclntsh.so.
If using an RPM-based installation of Oracle Instant Client, the configure line will look like this:
./configure --with-oci8=shared,instantclient,/usr/lib/oracle/<version>/client/lib
For example, --with-oci8=shared,instantclient,/usr/lib/oracle/12.1/client/lib
Note that Oracle Instant Client support first appeared in PHP 4.3.11 and 5.0.4 and originally used the option --with-oci8-instant-client to configure PHP.
If using an Oracle database or full Oracle Client installation then do:
./configure --with-oci8=shared,$ORACLE_HOME
Make sure the web server user
(nobody, www) has access to
the libraries, initialization files
and tnsnames.ora (if used) under
the $ORACLE_HOME directory. With Oracle
10gR2, you may need to run
the $ORACLE_HOME/install/changePerm.sh
utility to give directory access.
After configuration, follow the usual PHP building procedure, e.g. make install. The OCI8 shared extension oci8.so library will be created. It may need to be manually moved to the PHP extension directory, specified by the extension_dir option in your php.ini file.
To complete installation of OCI8, edit php.ini and add the line:
extension=oci8.so
Configure PHP to include OCI8 using one of the following configure options.
If using Oracle Instant Client, then do:
./configure --with-oci8=instantclient,/path/to/instant/client/lib
If using an Oracle database or full Oracle Client installation then do:
./configure --with-oci8=$ORACLE_HOME
After configuration, follow the usual PHP building procedure, e.g. make install. After successful compilation, you do not need to add oci8.so to php.ini. No additional build steps are required.
The OCI8 extension can be added to an existing PHP installation either automatically or manually from » PECL.
For an automated install follow these steps:
If you are behind a firewall, set PEAR's proxy, for example:
pear config-set http_proxy http://my-proxy.example.com:80/
Run
pecl install oci8
When prompted, enter either the value of $ORACLE_HOME, or
instantclient,/path/to/instant/client/lib.
Note: Do not enter the variable $ORACLE_HOME
because it will not be expanded. Instead, enter the actual path
of the Oracle home directory.
For a manual install when the pecl command is not
available, download the PECL OCI8 package, e.g. oci8-1.4.10.tgz.
Extract the package:
tar -zxf oci8-1.4.10.tgz cd oci8-1.4.10
Prepare the package:
phpize
Configure the package, either
using $ORACLE_HOME or Instant Client
./configure -with-oci8=shared,$ORACLE_HOME
or
./configure -with-oci8=shared,instantclient,/path/to/instant/client/lib
Install the package:
make install
After either an automatic or manual install, edit your php.ini file and add the line:
extension=oci8.so
Make sure the php.ini directive extension_dir is set to the directory that oci8.so was installed in.
When using Oracle 10gR2 client libraries on
Windows, uncomment the php.ini
line extension=php_oci8.dll. When using Oracle
11gR2 or later client libraries, uncomment
extension=php_oci8_11g.dll
or extension=php_oci8.dll. With Oracle
12c libraries
use extension=php_oci8_12c.dll
or extension=php_oci8_11g.dll
or extension=php_oci8.dll. Only one of these DLLs
may be enabled at a time. DLLs with higher versions may contain more
functionality. Not all DLLs may be available for all versions of
PHP. Make
sure extension_dir is set
to the directory containing the PHP extension DLLs.
If using Instant Client, set the system PATH environment variable to the Oracle library directory.
Before using this extension, make sure that the Oracle environment variables are properly set for the web daemon user. If your web server is automatically started at boot time then make sure that the boot-time environment is also configured correctly.
Note:
Do not set Oracle environment variables using putenv() in a PHP script because Oracle libraries may be loaded and initialized before your script runs. Variables set with putenv() may then cause conflicts, crashes, or unpredictable behavior. Some functions may work but others might give subtle errors. The variables should be set up before the web server is started.
On Red Hat Linux and variants, export variables at the end of
/etc/sysconfig/httpd. Other systems with
Apache 2 may use an envvars script in the
Apache bin directory. A third option, the
Apache SetEnv directive
in httpd.conf, may work in some systems but is
known to be insufficient in others.
To check that environment variables are set correctly, use phpinfo() and check the Environment (not the Apache Environment) section contains the expected variables.
The variables that might be needed are included in the following table. Refer to the Oracle documentation for more information on all the available variables.
| Name | Purpose |
|---|---|
| ORACLE_HOME | Contains the directory of the full Oracle Database software. Do not set this when using Oracle Instant Client as it is unnecessary and may cause installation problems. |
| ORACLE_SID | Contains the name of the database on the local machine to be connected to. There is no need to set this if you using Oracle Instant Client, or always pass the connection parameter to oci_connect(). |
| LD_LIBRARY_PATH | Set this (or its platform equivalent, such
as DYLD_LIBRARY_PATH, LIBPATH,
or SHLIB_PATH) to the location of the Oracle
libraries, for example $ORACLE_HOME/lib
or /usr/lib/oracle/11.1/client/lib. This
variable is not needed if the libraries are located by a
different search mechanism, such as
with ldconfig or
with LD_PRELOAD. |
| NLS_LANG | This is the primary variable for setting the character set and globalization information used by the Oracle libraries. |
| ORA_SDTZ | Sets the Oracle session timezone. |
| TNS_ADMIN | Contains the directory where the Oracle Net Services
configuration files such as tnsnames.ora
and sqlnet.ora are kept. Not needed if
the oci_connect() connection string uses the
Easy Connect naming syntax such
as localhost/XE. Not needed if the network
configuration files are in one of the default locations such
as $ORACLE_HOME/network/admin
or /etc. |
TWO_TASK, ORA_TZFILE, and the
various Oracle globalization settings
like NLS* and the ORA_NLS_*
variables.
The most common problem with installing OCI8 is not having the Oracle environment correctly set. This typically appears as a problem using oci_connect() or oci_pconnect(). The error may be a PHP error such as Call to undefined function oci_connect(), an Oracle error such as ORA-12705, or even an Apache crash. Check the Apache log files for startup errors and see the sections above to resolve this problem.
While network errors like ORA-12154 or ORA-12514 indicate an Oracle network naming or configuration issue, the root cause may be because the PHP environment is incorrectly set up and Oracle libraries are unable to locate the tnsnames.ora configuration file.
On Windows, having multiple versions of Oracle on the one machine can easily cause library clashes unless care is taken to make sure PHP only uses the correct version of Oracle.
A utility to examine what libraries are being looked for and loaded can help resolve missing or clashing library issues, particularly on Windows.
Note: If the web server doesn't start or crashes at startup
Check that Apache is linked with the pthread library:
# ldd /www/apache/bin/httpd libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000) libm.so.6 => /lib/libm.so.6 (0x4002f000) libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000) libdl.so.2 => /lib/libdl.so.2 (0x4007a000) libc.so.6 => /lib/libc.so.6 (0x4007e000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)If the libpthread is not listed, then reinstall Apache:
# cd /usr/src/apache_1.3.xx # make clean # LIBS=-lpthread ./config.status # make # make installPlease note that on some systems like UnixWare, it is libthread instead of libpthread. PHP and Apache have to be configured with EXTRA_LIBS=-lthread.
The OCI8 test suite is in ext/oci8/tests. After OCI8 tests are run this directory will also contain logs of any failures.
Before running PHP's tests, edit details.inc
and set $user, $password and the $dbase connection string. The
OCI8 test suite has been developed using
the SYSTEM account. Some tests will fail if
the test user does not have equivalent permissions.
If Oracle Database Resident Connection Pooling is being
tested, set $test_drcp to TRUE and ensure the
connection string uses an appropriate DRCP pooled server.
An alternative to editing details.inc is the set environment variables, for example:
$ export PHP_OCI8_TEST_USER=system
$ export PHP_OCI8_TEST_PASS=oracle
$ export PHP_OCI8_TEST_DB=localhost/XE
$ export PHP_OCI8_TEST_DRCP=FALSE
Next, set any necessary environment for the Oracle database. With Oracle 10gR2 XE do:
$ . /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/oracle_env.sh
With Oracle 11gR2 XE do:
$ . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh
For other versions of the Oracle database do:
$ . /usr/local/bin/oraenv
Some shells require that php.ini has E in the
variables_order parameter, for example:
variables_order = "EGPCS"
Run all the PHP tests with:
$ cd your_php_src_directory
$ make test
$ cd your_php_src_directory
$ make test TESTS=ext/oci8
When the tests have completed, review any test failures. On slow
systems, some tests may take longer than the default test
timeout in run-tests.php. To correct this,
set the environment variable TEST_TIMEOUT to
a larger number of seconds.
On fast machines with a local database configured for light load
(e.g. Oracle 11gR2 XE) some tests might fail with ORA-12516 or
ORA-12520 errors. To prevent this, increase the database
PROCESSES parameter using the following steps:
Connect as the oracle software owner:
$ su - oracle
Set the necessary Oracle environment with oracle_env.sh or oraenv, as described above.
Start the SQL*Plus command line tool and
increase PROCESSES
$ sqlplus / as sysdba
SQL> alter system set processes=100 scope=spfile
Restart the database:
SQL> startup force
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| oci8.connection_class | "" | PHP_INI_ALL | Available since PHP 5.3 (PECL OCI8 1.3). |
| oci8.default_prefetch | "100" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1). |
| oci8.events | Off | PHP_INI_SYSTEM | Available since PHP 5.3 (PECL OCI8 1.3). |
| oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1). |
| oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1). |
| oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1). |
| oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1). |
| oci8.privileged_connect | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1). |
| oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1). |
Here's a short explanation of the configuration directives.
oci8.connection_class
string
This user defined text is used by Oracle 11g Database Resident Connection Pooling (DRCP) connections to sub-partition the connection pool. It allows OCI8 persistent connections from an application to reuse database sessions from a previous PHP script, giving better scalability. When an application uses a database pooled process previously used with a different connection class, the session settings such as the default Oracle date format are reset. This prevents accidental sharing of information between different applications.
The value can be set at runtime with ini_set() prior to connecting.
To use DRCP, OCI8 must be linked with Oracle 11g libraries
and the database must be Oracle 11g. The connection pool
must be enabled in the database,
the oci8.connection_class should be set to
the same string for all web servers running the same
application, and the OCI8 connection string must specify to
use a pooled server.
oci8.default_prefetch
int
This option sets the default number of extra rows that will
be fetched and cached automatically whenever a low-level
request for data from the database is made. Setting a value
of 0 turns off prefetching.
The prefetch value does not alter the number of rows that functions like oci_fetch_array() return to the user; the prefetching and caching of rows is handled internally in OCI8.
The value can be set per-statement with oci_set_prefetch() prior to statement execution.
In PHP 5.3 (PECL OCI8 1.3.4) the default value was increased
from 10 to 100.
In PHP 5.3.2 (PECL OCI8 1.4) the minimum value settable was
reduced from 1 to 0,
allowing prefetching to be turned off.
When using Oracle Database 12c or later, the prefetch
value set by PHP can be overridden by Oracle's
client oraaccess.xml configuration file. Refer
to Oracle documentation for more detail.
Note: A larger prefetch can result in improved performance, at the cost of some increased memory usage. For queries that return large amounts of data, the performance benefit can be significant.
oci8.events
boolean
Using On allows PHP to be notified of
database Fast Application Notification (FAN) events.
Without FAN, when a database instance or machine node fails unexpectedly, PHP applications may be blocked waiting for a database response until a TCP timeout expires. With FAN events, PHP applications are quickly notified of failures that affect their established database connections. The OCI8 extension will clean up unusable connections in the persistent connection cache.
When using On, the database must also be
configured to post FAN events.
FAN support is available when OCI8 is linked with Oracle 10gR2 (or later) libraries and connected to Oracle Database 10gR2 (or later).
oci8.max_persistent
int
The maximum number of persistent OCI8 connections per PHP process. Setting this option to -1 means that there is no limit.
oci8.old_oci_close_semantics
boolean
This option controls oci_close() behaviour. Enabling it means that oci_close() will do nothing; the connection will not be closed until the end of the script. This is for backward compatibility only. If you find that you need to enable this setting, you are strongly encouraged to adjust the oci_close() calls in your application instead of enabling this option.
oci8.persistent_timeout
int
The maximum number of seconds that a PHP process is allowed to keep an idle persistent connection open. Setting this option to -1 means that idle persistent connections will be retained until the PHP process terminates or the connection is explicitly closed with oci_close().
Note: In PHP, the expiry of idle resources is not alarm-based. It occurs when PHP finishes processing a script and checks the last-used timestamp of resources. Hence there is a paradox that idle connections can only be closed when there is some activity (though not necessarily OCI8 related) in the PHP process. If there is more than one PHP process then each must individually be activated in order to trigger expiry of its idle resources. The introduction of Database Resident Connection Pooling (DRCP) in Oracle 11g resolves the memory and resource issues that
oci8.max_persistentandoci8.persistent_timeoutpreviously attempted to overcome.
Note: In PHP 5.3 (PECL OCI8 1.3), persistent connections can be closed with oci_close().
oci8.ping_interval
int
The number of seconds that must pass before issuing a ping during oci_pconnect(). A ping ensures that the database connection is valid. When set to 0, persistent connections will be pinged every time oci_pconnect() is called. To disable pings completely, set this option to -1.
Note: Disabling pings allows oci_pconnect() to operate at the highest efficiency, but PHP may not be able to detect unusable connections, such as caused by network dropout, or if the Oracle database has gone down since PHP connected, until the connection is used later in the script. Consult the oci_pconnect() documentation for more information.
oci8.privileged_connect
boolean
This option allows connections to use the privileged external
credentials
OCI_SYSOPER or OCI_SYSDBA.
Note: Seting this
Oncan allow scripts on web servers running with the appropriate OS user privileges to connect as privileged database users without requiring a database password. This can be a security risk.
oci8.statement_cache_size
int
This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.
Statement caching removes the need to transmit the statement text to the database and removes the need to transmit any meta data about the statement back to PHP. This can significantly improve overall system performance in applications which reuse statements during the lifetime of a connection. Some extra database "cursors" may be held open under the assumption that statements will be reused.
Set this value to the size of the working set of statements used by your application. Setting too small a value can cause statements to be flushed from the cache before they are reused.
This option is of most use with persistent connections.
When using Oracle Database 12c, this
value can be overridden and automatically tuned by Oracle's
client oraaccess.xml file. Refer to
Oracle documentation for more detail.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
| Constant | Description |
|---|---|
OCI_ASSOC |
Used with oci_fetch_all() and oci_fetch_array() to get results as an associative array. |
OCI_BOTH |
Used with oci_fetch_all() and oci_fetch_array() to get results as an array with both associative and number indices. |
OCI_COMMIT_ON_SUCCESS |
Statement execution mode for oci_execute() call. Automatically commit changes when the statement has succeeded. |
OCI_CRED_EXT |
Used with oci_connect() for using Oracles' External or OS authentication. Introduced in PHP 5.3 and PECL OCI8 1.3.4. |
OCI_DEFAULT |
See OCI_NO_AUTO_COMMIT.
|
OCI_DESCRIBE_ONLY |
Statement execution mode for oci_execute(). Use this mode if you want meta data such as the column names but don't want to fetch rows from the query. |
OCI_EXACT_FETCH |
Obsolete. Statement fetch mode. Used when the application knows in advance exactly how many rows it will be fetching. This mode turns prefetching off for Oracle release 8 or later mode. The cursor is canceled after the desired rows are fetched which may result in reduced server-side resource usage. |
OCI_FETCHSTATEMENT_BY_COLUMN |
Default mode of oci_fetch_all(). |
OCI_FETCHSTATEMENT_BY_ROW |
Alternative mode of oci_fetch_all(). |
OCI_LOB_BUFFER_FREE |
Used with OCI-Lob::flush to free buffers used. |
OCI_NO_AUTO_COMMIT |
Statement execution mode
for oci_execute(). The transaction is not
automatically committed when using this mode. For
readability in new code, use this value instead of the
older, equivalent OCI_DEFAULT constant.
Introduced in PHP 5.3.2 (PECL OCI8 1.4).
|
OCI_NUM |
Used with oci_fetch_all() and oci_fetch_array() to get results as an enumerated array. |
OCI_RETURN_LOBS |
Used with oci_fetch_array() to get the data value of the LOB instead of the descriptor. |
OCI_RETURN_NULLS |
Used with oci_fetch_array() to get empty
array elements if the row items value is NULL.
|
OCI_SEEK_CUR |
Used with OCI-Lob::seek to set the seek position. |
OCI_SEEK_END |
Used with OCI-Lob::seek to set the seek position. |
OCI_SEEK_SET |
Used with OCI-Lob::seek to set the seek position. |
OCI_SYSDATE |
Obsolete. |
OCI_SYSDBA |
Used with oci_connect() to connect with the SYSDBA privilege. The php.ini setting oci8.privileged_connect should be enabled to use this. |
OCI_SYSOPER |
Used with oci_connect() to connect with the SYSOPER privilege. The php.ini setting oci8.privileged_connect should be enabled to use this. |
OCI_TEMP_BLOB |
Used with OCI-Lob::writeTemporary to indicate that a temporary BLOB should be created. |
OCI_TEMP_CLOB |
Used with OCI-Lob::writeTemporary to indicate that a temporary CLOB should be created. |
| Constant | Description |
|---|---|
OCI_B_BFILE |
Used with oci_bind_by_name() when binding BFILEs. |
OCI_B_BIN |
Used with oci_bind_by_name() to bind RAW values. |
OCI_B_BLOB |
Used with oci_bind_by_name() when binding BLOBs. |
OCI_B_BOL |
Used with oci_bind_by_name() to bind a PL/SQL BOOLEAN variable. |
OCI_B_CFILEE |
Used with oci_bind_by_name() when binding CFILEs. |
OCI_B_CLOB |
Used with oci_bind_by_name() when binding CLOBs. |
OCI_B_CURSOR |
Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor(). |
OCI_B_INT |
Used with oci_bind_array_by_name() to bind arrays of INTEGER. |
OCI_B_NTY |
Used with oci_bind_by_name() when binding
named data types. Note: in PHP < 5.0 it was called
OCI_B_SQLT_NTY.
|
OCI_B_NUM |
Used with oci_bind_array_by_name() to bind arrays of NUMBER. |
OCI_B_ROWID |
Used with oci_bind_by_name() when binding ROWIDs. |
SQLT_AFC |
Used with oci_bind_array_by_name() to bind arrays of CHAR. |
SQLT_AVC |
Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. |
SQLT_BDOUBLE |
Not supported. |
SQLT_BFILEE |
The same as OCI_B_BFILE.
|
SQLT_BFLOAT |
Not supported. |
SQLT_BIN |
The same as OCI_B_BIN.
|
SQLT_BLOB |
The same as OCI_B_BLOB.
|
SQLT_BOL |
The same as OCI_B_BOL.
|
SQLT_CFILEE |
The same as OCI_B_CFILEE.
|
SQLT_CHR |
Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. Also used with oci_bind_by_name(). |
SQLT_CLOB |
The same as OCI_B_CLOB.
|
SQLT_FLT |
Used with oci_bind_array_by_name() to bind arrays of FLOAT. |
SQLT_INT |
The same as OCI_B_INT.
|
SQLT_LBI |
Used with oci_bind_by_name() to bind LONG RAW values. |
SQLT_LNG |
Used with oci_bind_by_name() to bind LONG values. |
SQLT_LVC |
Used with oci_bind_array_by_name() to bind arrays of LONG VARCHAR. |
SQLT_NTY |
The same as OCI_B_NTY.
|
SQLT_NUM |
The same as OCI_B_NUM.
|
SQLT_ODT |
Used with oci_bind_array_by_name() to bind arrays of LONG. |
SQLT_RDD |
The same as OCI_B_ROWID.
|
SQLT_RSET |
The same as OCI_B_CURSOR.
|
SQLT_STR |
Used with oci_bind_array_by_name() to bind arrays of STRING. |
SQLT_UIN |
Not supported. |
SQLT_VCS |
Used with oci_bind_array_by_name() to bind arrays of VARCHAR. |
| Constant | Description |
|---|---|
OCI_DTYPE_FILE |
This flag tells oci_new_descriptor() to initialize a new FILE descriptor. |
OCI_DTYPE_LOB |
This flag tells oci_new_descriptor() to initialize a new LOB descriptor. |
OCI_DTYPE_ROWID |
This flag tells oci_new_descriptor() to initialize a new ROWID descriptor. |
OCI_D_FILE |
The same as OCI_DTYPE_FILE.
|
OCI_D_LOB |
The same as OCI_DTYPE_LOB.
|
OCI_D_ROWID |
The same as OCI_DTYPE_ROWID.
|
These examples connect as the HR user, which is
the sample "Human Resources" schema supplied with the
Oracle database. The account may need to be unlocked and the
password reset before you can use it.
The examples connect to the XE database on your
machine. Change the connect string to your database before running
the examples.
Example #1 Basic query
This shows querying and displaying results. Statements in OCI8 use a prepare-execute-fetch sequence of steps.
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Prepare the statement
$stid = oci_parse($conn, 'SELECT * FROM departments');
if (!$stid) {
$e = oci_error($conn);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Perform the logic of the query
$r = oci_execute($stid);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Fetch the results of the query
print "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
print "<tr>\n";
foreach ($row as $item) {
print " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
print "</tr>\n";
}
print "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 Inserting with bind variables
Bind variables improve performance by allowing reuse of execution contexts and caches. Bind variables improve security by preventing some kinds of SQL Injection problems.
<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (mid NUMBER, myd VARCHAR2(20));
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'INSERT INTO MYTABLE (mid, myd) VALUES(:myid, :mydata)');
$id = 60;
$data = 'Some data';
oci_bind_by_name($stid, ':myid', $id);
oci_bind_by_name($stid, ':mydata', $data);
$r = oci_execute($stid); // executes and commits
if ($r) {
print "One row inserted";
}
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 Binding in the WHERE clause of a query
This shows a single scalar bind.
<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['LAST_NAME'] ."<br>\n";
}
// Output is
// Austin
// Ernst
// Hunold
// Lorentz
// Pataballa
oci_free_statement($stid);
oci_close($conn);
?>
Example #4 Inserting and fetching a CLOB
For large data use binary long object (BLOB) or character long object (CLOB) types. This example uses CLOB.
<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (mykey NUMBER, myclob CLOB);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$mykey = 12343; // arbitrary key for this example;
$sql = "INSERT INTO mytable (mykey, myclob)
VALUES (:mykey, EMPTY_CLOB())
RETURNING myclob INTO :myclob";
$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_NO_AUTO_COMMIT); // use OCI_DEFAULT for PHP <= 5.3.1
$clob->save("A very long string");
oci_commit($conn);
// Fetching CLOB data
$query = 'SELECT myclob FROM mytable WHERE mykey = :mykey';
$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);
print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) {
print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
unset($row);
}
print '</table>';
?>
Example #5 Using a PL/SQL stored function
You must bind a variable for the return value and optionally for any PL/SQL function arguments.
<?php
/*
Before running the PHP program, create a stored function in
SQL*Plus or SQL Developer:
CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
BEGIN
RETURN p * 3;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$p = 8;
$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);
oci_bind_by_name($stid, ':r', $r, 40);
oci_execute($stid);
print "$r\n"; // prints 24
oci_free_statement($stid);
oci_close($conn);
?>
Example #6 Using a PL/SQL stored procedure
With stored procedures, you should bind variables for any arguments.
<?php
/*
Before running the PHP program, create a stored procedure in
SQL*Plus or SQL Developer:
CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
BEGIN
p2 := p1 * 2;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$p1 = 8;
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);
oci_execute($stid);
print "$p2\n"; // prints 16
oci_free_statement($stid);
oci_close($conn);
?>
Example #7 Calling a PL/SQL function that returns a REF CURSOR
Each returned value from the query is a REF
CURSOR that can be fetched from.
<?php
/*
Create the PL/SQL stored function as:
CREATE OR REPLACE FUNCTION myfunc(p1 IN NUMBER) RETURN SYS_REFCURSOR AS
rc SYS_REFCURSOR;
BEGIN
OPEN rc FOR SELECT city FROM locations WHERE ROWNUM < p1;
RETURN rc;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT myfunc(5) AS mfrc FROM dual');
oci_execute($stid);
echo "<table border='1'>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
echo "<tr>\n";
$rc = $row['MFRC'];
oci_execute($rc); // returned column value from the query is a ref cursor
while (($rc_row = oci_fetch_array($rc, OCI_ASSOC))) {
echo " <td>" . $rc_row['CITY'] . "</td>\n";
}
oci_free_statement($rc);
echo "</tr>\n";
}
echo "</table>\n";
// Output is:
// Beijing
// Bern
// Bombay
// Geneva
oci_free_statement($stid);
oci_close($conn);
?>
The OCI8 extension provides three different functions for connecting to Oracle. The standard connection function is oci_connect(). This creates a connection to an Oracle database and returns a resource used by subsequent database calls.
Connecting to an Oracle server is a reasonably expensive operation in terms of the time that it takes to complete. The oci_pconnect() function uses a persistent cache of connections that can be re-used across different script requests. This means that the connection overhead will typically only occur once per PHP process (or Apache child).
If the application connects to Oracle using a different set of credentials for each web user, the persistent cache employed by oci_pconnect() will become less useful as the number of concurrent users increases, to the point where it may start to adversely affect the overall performance of the Oracle server due to maintaining too many idle connections. If the application is structured in this way, it is recommended to either tune the application using the oci8.max_persistent and oci8.persistent_timeout configuration settings (these will give control over the persistent connection cache size and lifetime), use Oracle Database Resident Connection Pooling (in Oracle Database 11g or later), or use oci_connect() instead.
Both oci_connect() and oci_pconnect() employ a connection cache; if multiple calls to oci_connect() use the same parameters in a given script, the second and subsequent calls return the existing connection handle. The cache used by oci_connect() is cleaned up at the end of the script run, or when the connection handle is explicitly closed. The function oci_pconnect() has similar behavior, although its cache is maintained separately and survives between HTTP requests.
This caching feature means the two handles are not transactionally isolated (they are in fact the same connection handle, so there is no isolation of any kind). If the application needs two separate, transactionally isolated connections, then use oci_new_connect().
The oci_pconnect() cache is cleared and any database connections closed when the PHP process terminates, so effective use of persistent connections requires that PHP be an Apache module or used with FCGI, or similar. Persistent connections will not have any benefits over oci_connect() when PHP is used with CGI or via the command-line.
The function oci_new_connect() always creates a new connection to the Oracle server, regardless of what other connections might already exist. High traffic web applications should avoid using oci_new_connect(), especially in the busiest sections of the application.
PHP from 5.3 (PECL OCI8 1.3) supports Oracle Database Resident Connection Pooling (DRCP). DRCP allows more efficient use of database machine memory and provides high scalability. No, or minimal, application changes are needed to use DRCP.
DRCP is suited for applications that connect using few database
schemas and hold database connections open for a short period of
time. Other applications should use Oracle's
default Dedicated database server processes, or
use Shared servers.
DRCP benefits all three connection functions, but gives the highest scalability when connections are created with oci_pconnect().
For DRCP to be available in OCI8, Oracle client libraries used by PHP and the version of the Oracle Database must both be 11g or greater.
Documentation on DRCP is found in several Oracle manuals. For example, see » Configuring Database Resident Connection Pooling in the Oracle documentation for usage information. A » DRCP white paper contains background information on DRCP.
To use DRCP, build PHP with the OCI8 1.3 (or later) extension and Oracle 11g (or later) libraries and then follow these steps:
As a privileged database administrator, use a program like SQL*Plus to start the connection pool in the database:
SQL> execute dbms_connection_pool.start_pool;
Optionally
use dbms_connection_pool.alter_param() to
configure DRCP settings. The current pool settings can be
queried from the DBA_CPOOL_INFO view.
Update the connection strings used. For PHP applications that
currently connect using a Network Connect Name
like MYDB:
$c = oci_pconnect("myuser", "mypassword", "MYDB");
modify the tnsnames.ora file and add
a (SERVER=POOLED) clause, for example:
MYDB = (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=myhost.dom.com)
(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)
(SERVER=POOLED)))
Alternatively, modify the Easy Connect syntax in PHP and add
:POOLED after the service name:
$c = oci_pconnect("myuser", "mypassword", "myhost.dom.com:1521/sales:POOLED");
Edit php.ini and choose a connection class name. This name indicates a logical division of the connection pool and can be used to isolate pooling for separate applications. Any PHP applications with the same user name and connection class value will be able to share connections in the pool, giving greater scalability.
oci8.connection_class = "MY_APPLICATION_NAME"
Run the application, connecting to the 11g (or later) database.
Note:
Applications using Oracle 10g that require the performance of persistent connections can reduce the amount of database server memory needed by using Oracle
Sharedservers (previously known as Multi Threaded Servers). Refer to Oracle documentation for information.
Changing a password over DRCP connections will fail with the error ORA-56609: Usage not supported with DRCP. This is a documented restriction of Oracle Database 11g.
From OCI8 1.3, persistent connections can be closed by the user, allowing greater control over connection resource usage. Persistent connections will now also be closed automatically when there is no PHP variable referencing them, such as at the end of scope of a PHP user function. This will rollback any uncommitted transaction. These changes to persistent connections make them behave similarly to non-persistent connections, simplifying the interface, allowing for greater application consistency and predictability. Use oci8.old_oci_close_semantics set to On to retain the historical behavior.
If the Oracle Database is version 11.1.0.6, then the Oracle database patch for Oracle bug 6474441 must be applied to use DRCP. Without this patch, errors such as ORA-01000: maximum open cursors exceeded, ORA-01001 invalid cursor or ORA-01002 fetch out of sequence may occur. This bug was fixed in Oracle 11.1.0.7 onwards.
If the Oracle 11.1.0.6 database patch cannot be applied, one of the following three workarounds can be used instead:
Dedicated
or Shared servers instead of DRCP.
Oracle Database 11.1.0.7 and the Oracle Database 11.1.0.6 patch for
Oracle bug 6474441 allow PHP applications with DRCP connection to
use a database LOGON trigger to set session
properties at the time of session creation. Examples of such
settings are the NLS language and the date format.
If the Oracle 11.1.0.6 database patch cannot be applied, one of the
following workarounds can be used instead
of using LOGON triggers:
Dedicated
or Shared servers instead of DRCP.
The automatic re-establishment of PHP persistent connections after
an Apache or FCGI process respawns means LOGON
triggers in PHP are only recommended for setting session attributes
and not for per-application user connection requests. This is even
more so with DRCP due to the automatic pool sizing and with the
way LOGON triggers fire with DRCP
authentication.
FAN support gives fast connection failover, an Oracle Database high availability feature. This allows PHP OCI8 scripts to be notified when a database machine or database instance becomes unavailable. Without FAN, OCI8 can hang until a TCP timeout occurs and an error is returned, which might be several minutes. Enabling FAN in OCI8 can allow applications to detect errors and re-connect to an available database instance without the web user being aware of an outage.
FAN support is available when the Oracle client libraries that PHP links with and the Oracle Database are either version 10gR2 or later.
FAN benefits users of Oracle's clustering technology (RAC) because connections to surviving database instances can be immediately made. Users of Oracle's Data Guard with a broker will see the FAN events generated when the standby database goes online. Standalone databases will send FAN events when the database restarts.
For active connections, when a machine or database instance becomes unavailable, a connection failure error will be returned by the OCI8 extension function currently being called. On a subsequent PHP script re-connect, a connection to a surviving database instance will be established. The OCI8 extension also transparently cleans up any idle connections affected by a database machine or instance failure so PHP connect calls will establish a fresh connection without the script being aware of any service disruption.
When oci8.events
is On, it is suggested to
set oci8.ping_interval
to -1 to disable pinging, since enabling FAN events provide
pro-active connection management of idle connections made invalid
by a service disruption.
To enable FAN support in PHP OCI8, build PHP OCI8 with Oracle 10gR2 or later libraries and then follow these steps:
SQL> execute dbms_service.modify_service(
SERVICE_NAME => 'sales',
AQ_HA_NOTIFICATIONS => TRUE);
oci8.events = On
TAF is an Oracle Database feature that provides high availability. It enables PHP OCI8 applications to automatically reconnect to a preconfigured database when database connectivity fails due to instance or network failure.
In a configured Oracle Database system, TAF occurs when the PHP application detects that the database instance is down or unreachable. It establishes a connection to another node in an Oracle » RAC configuration, a hot standby database, or the same database instance itself. See » Oracle Call Interface Programmer's Guide for more information about OCI TAF.
An application callback can be registered with oci_register_taf_callback(). During failover, normal application processing stops and the registered callback is invoked. The callback notifies the application of the failover events. If the failover succeeds, normal processing will be resumed. If the failover aborts, any following database operations in the application will fail due to no connection being available.
When a connection fails over to another database, the callback can reset any necessary connection state, for example replaying any necessary ALTER SESSION commands if the database service did not have -failover_restore enabled.
An application callback can be removed by calling oci_unregister_taf_callback().
TAF can be configured on the PHP OCI8 side or in the database configuration. If both are configured, database-side settings take precedence.
Configure TAF in PHP OCI8 (the client side) by including the FAILOVER_MODE parameter in the CONNECT_DATA portion of a connect descriptor. See Configuring Transparent Application Failover in » Oracle Database Net Services Administrator's Guide for more information about client side configuration of TAF.
An example tnsnames.ora to configure TAF reconnecting to the same database instance:
ORCL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
(CONNECT_DATA =
(SERVICE_NAME = orclpdb1)
(FAILOVER_MODE =
(TYPE = SELECT)
(METHOD = BASIC)
(RETRIES = 20)
(DELAY = 15))))
Alternatively configure TAF on the database side by modifying the target service with » srvctl (for RAC) or the » DBMS_SERVICE.MODIFY_SERVICE packaged procedure (for single instance databases).
A TAF callback is an application function that can be registered to be called during failover. It is called several times while re-establishing the application's connection.
Callback first occurs when a loss of connection is detected. This allows the application to act accordingly for the upcoming delay of the failover. If the failover is successful, the callback is invoked after connection is re-established and usable. At this time, the application can resynchronize session settings and take actions such as informing the user that failover occurred. If failover is unsuccessful, a callback occurs to inform the application that a failover did not take place and the connection is unusable.
The interface of a TAF user-defined callback function is as follows:
$connection
, int $event
, int $type
) : int
connectionThe Oracle connection on which the TAF callback was registered via oci_register_taf_callback(). The connection is not valid until the failover completes successfully.
eventThe failover event indicates the current status of the failover.
OCI_FO_BEGIN indicates that
failover has detected a lost connection and failover
is starting.
OCI_FO_END indicates successful
completion of failover.
OCI_FO_ABORT indicates that
failover was unsuccessful, and there is no option
of retrying.
OCI_FO_ERROR also indicates
that failover was unsuccessful, but it gives the
application the opportunity to handle the error
and return OCI_FO_RETRY to retry failover.
OCI_FO_REAUTH indicates
that an Oracle user has been re-authenticated.
typeThe failover type. This lets the callback know what type of failover the application has requested. The usual values are as follows:
OCI_FO_SESSION indicates that
the user has requested only session failover. For
example, if a user's connection is lost, then a
new session is automatically created for the user
on the backup. This type of failover does not
attempt to recover SELECTs.
OCI_FO_SELECT indicates that
the user has requested SELECT failover as well.
It allows users with open cursors to continue
fetching from them after failure.
return value
0 indicates the failover
steps should continue normally.
OCI_FO_RETRY indicates that
the failover should be attempted again by Oracle.
In case of an error while failing over to a new
connection, TAF is able to retry the failover.
Typically, the application code should sleep for
a while before returning OCI_FO_RETRY.
The following example registers a TAF callback
<?php
// Define userspace callback
class MyClass {
public static $retry_count;
public static function TAFCallback($conn, $event, $type)
{
switch ($event) {
case OCI_FO_BEGIN:
printf(" Failing Over ... Please stand by\n");
printf(" Failover type was found to be %s \n",
(($type==OCI_FO_SESSION) ? "SESSION"
:(($type==OCI_FO_SELECT) ? "SELECT" : "UNKNOWN!")));
self::$retry_count = 0;
break;
case OCI_FO_ABORT:
// The application cannot continue using the database
printf(" Failover aborted. Failover will not take place.\n");
break;
case OCI_FO_END:
// Failover completes successfully. Inform users a failover occurs.
printf(" Failover ended ... resuming services\n");
break;
case OCI_FO_REAUTH:
printf(" Failed over user ... resuming services\n");
// Replay any ALTER SESSION commands associated with this connection
// eg. oci_parse($conn, ‘ALTER SESSION …’) ;
break;
case OCI_FO_ERROR:
// Stop retrying if we have already attempted for 20 times.
if (self::$retry_count >= 20)
return 0;
printf(" Failover error received. Sleeping...\n");
sleep(10);
self::$retry_count++;
return OCI_FO_RETRY; // retry failover
break;
default:
printf("Bad Failover Event: %d.\n", $event);
break;
}
return 0;
}
}
$fn_name = 'MyClass::TAFCallback';
$conn = oci_connect('hr', 'welcome', 'orcl');
$sysconn = oci_connect('system', 'oracle', 'orcl');
// Use a privileged connection to construct a SQL statement that will initiate failover
$sql = <<< 'END'
select unique 'alter system disconnect session '''||sid||','||serial#||''''
from v$session_connect_info
where sid = sys_context('USERENV', 'SID')
END;
$s = oci_parse($conn, $sql);
oci_execute($s);
$r = oci_fetch_array($s);
$disconnectssql = $r[0];
oci_register_taf_callback($conn, $fn_name); // Register TAFCallback to Oracle TAF
print("Parsing user query\n");
$sql = "select systimestamp from dual";
$stmt = oci_parse($conn, $sql);
// For example, if a connection loss occurs at this point, oci_execute() will
// detect the loss and failover begins. During failover, oci_execute() will
// invoke the TAF callback function several times. If the failover is successful,
// a new connection is transparently created and oci_execute() will continue as
// usual. The connection session settings can be reset in the TAF callback
// function. If the failover is aborted, oci_execute() will return an error
// because a valid connection is not available.
// Disconnect the user, which initiates failover
print("Disconnecting the user\n");
$discsql = oci_parse($sysconn, $disconnectssql);
oci_execute($discsql);
print("Executing user query\n");
$e = oci_execute($stmt);
if (!$e) {
$m = oci_error($stmt);
trigger_error("Could not execute statement: ". $m['message'], E_USER_ERROR);
}
$row = oci_fetch_array($stmt);
print($row[0] . "\n");
// do other SQL statements with the new connection, if it is valid
// $stmt = oci_parse($conn, . . .);
?>
OCI8 2.0 introduced static DTrace probes that can be used on operating systems that support DTrace. See DTrace Dynamic Tracing for an overview of PHP and DTrace.
To enable DTrace support in PHP OCI8, build OCI8 as a shared
extension after setting PHP_DTRACE.
$ export PHP_DTRACE=yes $ pecl install oci8
Edit php.ini, set extension_dir to the directory with the created oci8.so and also enable the extension by adding:
extension=oci8.so
If you install PHP OCI8 2.0 from PECL using phpize and
configure (instead
of pecl), you will still need to set
PHP_DTRACE=yes. This is because
the --enable-dtrace option will be ignored by the
limited configure script of a PECL bundle.
See Installation of PECL extensions for general PECL installation instructions.
| Probe Name | Probe Description | Probe Arguments |
|---|---|---|
oci8-connect-entry |
Initiated by oci_connect(), oci_pconnect() and oci_new_connect(). Fires before database connection is established. | char *username, char *dbname, char *charset, long session_mode, int persistent, int exclusive |
oci8-connect-return |
Fires at the end of connection. | void *connection |
oci8-check-connection |
Fires if an Oracle error might have caused the connection to become invalid. | void *connection, char *client_id, int is_open, long errcode, unsigned long server_status |
oci8-sqltext |
Fires when oci_parse() is executed. | void *connection, char *client_id, void *statement, char *sql |
oci8-connection-close |
Fires when the connection to the database is completely destroyed. | void *connection |
oci8-error |
Fires if an Oracle error occurs. | int status, long errcode |
oci8-execute-mode |
Fires at oci_execute() to show the execution mode. | void *connection, char *client_id, void *statement, unsigned int mode |
These probes are useful for tracing OCI8 scripts.
The connection and statement are the pointers to internal structures used for tracking PHP connections and executed statements.
The client_id is the value set by oci_set_client_identifier().
Core PHP also has static probes. See DTrace Static Probes in Core PHP.
| Probe Name |
|---|
oci8-connect-expiry |
oci8-connect-lookup |
oci8-connect-p-dtor-close |
oci8-connect-p-dtor-release |
oci8-connect-type |
oci8-sesspool-create |
oci8-sesspool-stats |
oci8-sesspool-type |
These probes are useful for OCI8 maintainers. Refer to the OCI8 source code for arguments and to see when the will fire.
To list available probes, start a PHP process and then run:
# dtrace -l
The output will be similar to:
ID PROVIDER MODULE FUNCTION NAME
[ . . . ]
17 phpoci22116 oci8.so php_oci_dtrace_check_connection oci8-check-connection
18 phpoci22116 oci8.so php_oci_do_connect oci8-connect-entry
19 phpoci22116 oci8.so php_oci_persistent_helper oci8-connect-expiry
20 phpoci22116 oci8.so php_oci_do_connect_ex oci8-connect-lookup
21 phpoci22116 oci8.so php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-close
22 phpoci22116 oci8.so php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-release
23 phpoci22116 oci8.so php_oci_do_connect oci8-connect-return
24 phpoci22116 oci8.so php_oci_do_connect_ex oci8-connect-type
25 phpoci22116 oci8.so php_oci_connection_close oci8-connection-close
26 phpoci22116 oci8.so php_oci_error oci8-error
27 phpoci22116 oci8.so php_oci_statement_execute oci8-execute-mode
28 phpoci22116 oci8.so php_oci_create_spool oci8-sesspool-create
29 phpoci22116 oci8.so php_oci_create_session oci8-sesspool-stats
30 phpoci22116 oci8.so php_oci_create_session oci8-sesspool-type
31 phpoci22116 oci8.so php_oci_statement_create oci8-sqltext
The Provider column values consist of phpoci and
the process id of the currently running PHP process.
The Function column refers to PHP's internal C implementation function names where each provider is located.
If a PHP process is not running, then no PHP probes will be shown.
This example shows the basics of the DTrace D scripting language.
Example #1 user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace
#!/usr/sbin/dtrace -Zs
#pragma D option quiet
php*:::oci8-connect-entry
{
printf("%lld: PHP connect-entry\n", walltimestamp);
printf(" credentials=\"%s@%s\"\n", arg0 ? copyinstr(arg0) : "", arg1 ? copyinstr(arg1) : "");
printf(" charset=\"%s\"\n", arg2 ? copyinstr(arg2) : "");
printf(" session_mode=%ld\n", (long)arg3);
printf(" persistent=%d\n", (int)arg4);
printf(" exclusive=%d\n", (int)arg5);
}
php*:::oci8-connect-return
{
printf("%lld: PHP oci8-connect-return\n", walltimestamp);
printf(" connection=0x%p\n", (void *)arg0);
}
php*:::oci8-connection-close
{
printf("%lld: PHP oci8-connect-close\n", walltimestamp);
printf(" connection=0x%p\n", (void *)arg0);
}
php*:::oci8-error
{
printf("%lld: PHP oci8-error\n", walltimestamp);
printf(" status=%d\n", (int)arg0);
printf(" errcode=%ld\n", (long)arg1);
}
php*:::oci8-check-connection
{
printf("%lld: PHP oci8-check-connection\n", walltimestamp);
printf(" connection=0x%p\n", (void *)arg0);
printf(" client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
printf(" is_open=%d\n", arg2);
printf(" errcode=%ld\n", (long)arg3);
printf(" server_status=%lu\n", (unsigned long)arg4);
}
php*:::oci8-sqltext
{
printf("%lld: PHP oci8-sqltext\n", walltimestamp);
printf(" connection=0x%p\n", (void *)arg0);
printf(" client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
printf(" statement=0x%p\n", (void *)arg2);
printf(" sql=\"%s\"\n", arg3 ? copyinstr(arg3) : "");
}
php*:::oci8-execute-mode
{
printf("%lld: PHP oci8-execute-mode\n", walltimestamp);
printf(" connection=0x%p\n", (void *)arg0);
printf(" client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
printf(" statement=0x%p\n", (void *)arg2);
printf(" mode=0x%x\n", arg3);
}
This script uses the -Z option to
dtrace, allowing it to be run when there is no
PHP process executing. If this option were omitted the script
would immediately terminate when no PHP executable was running
because it knows none of the probes to be monitored are in
existence.
On multi-CPU machines the probe ordering might not appear to be sequential. This depends on which CPU was processing the probes, and how threads migrate across CPUs. Displaying probe time stamps helps reduce confusion.
The script traces all user-level PHP OCI8 static probe points throughout the duration of a running PHP script. Run the D script:
# ./user_oci8_probes.d
Run a PHP script or application. The monitoring D script will output each probe's arguments as it fires. For example, a simple PHP script that queries a table might produce the following trace output:
1381794982092854582: PHP connect-entry
credentials="hr@localhost/pdborcl"
charset=""
session_mode=0
persistent=0
exclusive=0
1381794982183158766: PHP oci8-connect-return
connection=0x7f4a7907bfb8
1381794982183594576: PHP oci8-sqltext
connection=0x7f4a7907bfb8
client_id="Chris"
statement=0x7f4a7907c2a0
sql="select * from employees"
1381794982183783706: PHP oci8-execute-mode
connection=0x7f4a7907bfb8
client_id="Chris"
statement=0x7f4a7907c2a0
mode=0x20
1381794982444344390: PHP oci8-connect-close
connection=0x7f4a7907bfb8
When monitoring is complete, the D script can be terminated with a
^C.
| Type | Mapping |
|---|---|
SQLT_NTY |
Maps a native collection type from a PHP collection object, such as those created by oci_new_collection(). |
SQLT_BFILEE |
Maps a native descriptor, such as those created by oci_new_descriptor(). |
SQLT_CFILEE |
Maps a native descriptor, such as those created by oci_new_descriptor(). |
SQLT_CLOB |
Maps a native descriptor, such as those created by oci_new_descriptor(). |
SQLT_BLOB |
Maps a native descriptor, such as those created by oci_new_descriptor(). |
SQLT_RDD |
Maps a native descriptor, such as those created by oci_new_descriptor(). |
SQLT_NUM |
Converts the PHP parameter to a 'C' long type, and binds to that value. |
SQLT_RSET |
Maps a native statement handle, such as those created by oci_parse() or those retrieved from other OCI queries. |
SQLT_BOL |
Bind the PHP parameter to a PL/SQL BOOLEAN |
SQLT_CHR and any other type |
Converts the PHP parameter to a string type and binds as a string. |
| Type | Mapping |
|---|---|
SQLT_RSET |
Creates an oci statement resource to represent the cursor. |
SQLT_RDD |
Creates a ROWID object. |
SQLT_BLOB |
Creates a LOB object. |
SQLT_CLOB |
Creates a LOB object. |
SQLT_BFILE |
Creates a LOB object. |
SQLT_LNG |
Bound as SQLT_CHR, returned as a string |
SQLT_LBI |
Bound as SQLT_BIN, returned as a string |
| Any other type | Bound as SQLT_CHR, returned as a string |
(PHP 5 >= 5.1.2, PHP 7, PECL OCI8 >= 1.2.0)
oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter
$statement
, string $name
, array &$var_array
, int $max_table_length
[, int $max_item_length = -1
[, int $type = SQLT_AFC
]] ) : bool
Binds the PHP array var_array to the Oracle
placeholder name, which points to an Oracle PL/SQL
array. Whether it will be used for input or output will be determined at
run-time.
statementA valid OCI statement identifier.
nameThe Oracle placeholder.
var_arrayAn array.
max_table_lengthSets the maximum length both for incoming and result arrays.
max_item_lengthSets maximum length for array items. If not specified or equals to -1, oci_bind_array_by_name() will find the longest element in the incoming array and will use it as the maximum length.
typeShould be used to set the type of PL/SQL array items. See list of available types below:
SQLT_NUM - for arrays of NUMBER.
SQLT_INT - for arrays of INTEGER (Note: INTEGER
it is actually a synonym for NUMBER(38), but
SQLT_NUM type won't work in this case even
though they are synonyms).
SQLT_FLT - for arrays of FLOAT.
SQLT_AFC - for arrays of CHAR.
SQLT_CHR - for arrays of VARCHAR2.
SQLT_VCS - for arrays of VARCHAR.
SQLT_AVC - for arrays of CHARZ.
SQLT_STR - for arrays of STRING.
SQLT_LVC - for arrays of LONG VARCHAR.
SQLT_ODT - for arrays of DATE.
Returns TRUE on success or FALSE on failure.
Example #1 oci_bind_array_by_name() example
<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$create = "CREATE TABLE bind_example(name VARCHAR(20))";
$stid = oci_parse($conn, $create);
oci_execute($stid);
$create_pkg = "
CREATE OR REPLACE PACKAGE ARRAYBINDPKG1 AS
TYPE ARRTYPE IS TABLE OF VARCHAR(20) INDEX BY BINARY_INTEGER;
PROCEDURE iobind(c1 IN OUT ARRTYPE);
END ARRAYBINDPKG1;";
$stid = oci_parse($conn, $create_pkg);
oci_execute($stid);
$create_pkg_body = "
CREATE OR REPLACE PACKAGE BODY ARRAYBINDPKG1 AS
CURSOR CUR IS SELECT name FROM bind_example;
PROCEDURE iobind(c1 IN OUT ARRTYPE) IS
BEGIN
-- Bulk Insert
FORALL i IN INDICES OF c1
INSERT INTO bind_example VALUES (c1(i));
-- Fetch and reverse
IF NOT CUR%ISOPEN THEN
OPEN CUR;
END IF;
FOR i IN REVERSE 1..5 LOOP
FETCH CUR INTO c1(i);
IF CUR%NOTFOUND THEN
CLOSE CUR;
EXIT;
END IF;
END LOOP;
END iobind;
END ARRAYBINDPKG1;";
$stid = oci_parse($conn, $create_pkg_body);
oci_execute($stid);
$stid = oci_parse($conn, "BEGIN arraybindpkg1.iobind(:c1); END;");
$array = array("one", "two", "three", "four", "five");
oci_bind_array_by_name($stid, ":c1", $array, 5, -1, SQLT_CHR);
oci_execute($stid);
var_dump($array);
?>
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_bind_by_name — Binds a PHP variable to an Oracle placeholder
$statement
, string $bv_name
, mixed &$variable
[, int $maxlength = -1
[, int $type = SQLT_CHR
]] ) : bool
Binds a PHP variable variable to the Oracle
bind variable placeholder bv_name. Binding
is important for Oracle database performance and also as a way to
avoid SQL Injection security issues.
Binding allows the database to reuse the statement context and caches from previous executions of the statement, even if another user or process originally executed it. Binding reduces SQL Injection concerns because the data associated with a bind variable is never treated as part of the SQL statement. It does not need quoting or escaping.
PHP variables that have been bound can be changed and the statement re-executed without needing to re-parse the statement or re-bind.
In Oracle, bind variables are commonly divided
into IN binds for values that are passed into
the database, and OUT binds for values that are
returned to PHP. A bind variable may be
both IN and OUT. Whether a
bind variable will be used for input or output is determined at
run-time.
You must specify maxlength when using
an OUT bind so that PHP allocates enough memory
to hold the returned value.
For IN binds it is recommended to set
the maxlength length if the statement is
re-executed multiple times with different values for the PHP
variable. Otherwise Oracle may truncate data to the length of the
initial PHP variable value. If you don't know what the maximum
length will be, then re-call oci_bind_by_name()
with the current data size prior to
each oci_execute() call. Binding an
unnecessarily large length will have an impact on process memory
in the database.
A bind call tells Oracle which memory address to read data from.
For IN binds that address needs to contain
valid data when oci_execute() is called. This
means that the variable bound must remain in scope until
execution. If it doesn't, unexpected results or errors such as
"ORA-01460: unimplemented or unreasonable conversion requested"
may occur. For OUT binds one symptom is no
value being set in the PHP variable.
For a statement that is repeatedly executed, binding values that never change may reduce the ability of the Oracle optimizer to choose the best statement execution plan. Long running statements that are rarely re-executed may not benefit from binding. However in both cases, binding might be safer than joining strings into a SQL statement, as this can be a security risk if unfiltered user text is concatenated.
statementA valid OCI8 statement identifer.
bv_name
The colon-prefixed bind variable placeholder used in the
statement. The colon is optional
in bv_name. Oracle does not use question
marks for placeholders.
variable
The PHP variable to be associated with bv_name
maxlength
Sets the maximum length for the data. If you set it to -1, this
function will use the current length
of variable to set the maximum
length. In this case the variable must
exist and contain data
when oci_bind_by_name() is called.
type
The datatype that Oracle will treat the data as. The
default type used
is SQLT_CHR. Oracle will convert the data
between this type and the database column (or PL/SQL variable
type), when possible.
If you need to bind an abstract datatype (LOB/ROWID/BFILE) you
need to allocate it first using the
oci_new_descriptor() function. The
length is not used for abstract datatypes
and should be set to -1.
Possible values for type are:
SQLT_BFILEE or OCI_B_BFILE
- for BFILEs;
SQLT_CFILEE or OCI_B_CFILEE
- for CFILEs;
SQLT_CLOB or OCI_B_CLOB
- for CLOBs;
SQLT_BLOB or OCI_B_BLOB
- for BLOBs;
SQLT_RDD or OCI_B_ROWID
- for ROWIDs;
SQLT_NTY or OCI_B_NTY
- for named datatypes;
SQLT_INT or OCI_B_INT - for integers;
SQLT_CHR - for VARCHARs;
SQLT_BIN or OCI_B_BIN
- for RAW columns;
SQLT_LNG - for LONG columns;
SQLT_LBI - for LONG RAW columns;
SQLT_RSET - for cursors created
with oci_new_cursor();
SQLT_BOL or OCI_B_BOL
- for PL/SQL BOOLEANs (Requires OCI8 2.0.7 and Oracle Database 12c)
Returns TRUE on success or FALSE on failure.
Example #1 Inserting data with oci_bind_by_name()
<?php
// Create the table with:
// CREATE TABLE mytab (id NUMBER, text VARCHAR2(40));
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn,"INSERT INTO mytab (id, text) VALUES(:id_bv, :text_bv)");
$id = 1;
$text = "Data to insert ";
oci_bind_by_name($stid, ":id_bv", $id);
oci_bind_by_name($stid, ":text_bv", $text);
oci_execute($stid);
// Table now contains: 1, 'Data to insert '
?>
Example #2 Binding once for multiple executions
<?php
// Create the table with:
// CREATE TABLE mytab (id NUMBER);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$a = array(1,3,5,7,11); // data to insert
$stid = oci_parse($conn, 'INSERT INTO mytab (id) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $v, 20);
foreach ($a as $v) {
$r = oci_execute($stid, OCI_DEFAULT); // don't auto commit
}
oci_commit($conn); // commit everything at once
// Table contains five rows: 1, 3, 5, 7, 11
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 Binding with a foreach() loop
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = 'SELECT * FROM departments WHERE department_name = :dname AND location_id = :loc';
$stid = oci_parse($conn, $sql);
$ba = array(':dname' => 'IT Support', ':loc' => 1700);
foreach ($ba as $key => $val) {
// oci_bind_by_name($stid, $key, $val) does not work
// because it binds each placeholder to the same location: $val
// instead use the actual location of the data: $ba[$key]
oci_bind_by_name($stid, $key, $ba[$key]);
}
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
foreach ($row as $item) {
print $item."<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Example #4 Binding in a WHERE clause
<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['LAST_NAME'] ."<br>\n";
}
// Output is
// Austin
// Ernst
// Hunold
// Lorentz
// Pataballa
oci_free_statement($stid);
oci_close($conn);
?>
Example #5 Binding with a LIKE clause
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
// Find all cities that begin with 'South'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE city LIKE :bv");
$city = 'South%'; // '%' is a wildcard in SQL
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['CITY'] as $c) {
print $c . "<br>\n";
}
// Output is
// South Brunswick
// South San Francisco
// Southlake
oci_free_statement($stid);
oci_close($conn);
?>
Example #6 Binding with REGEXP_LIKE
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
// Find all cities that contain 'ing'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE REGEXP_LIKE(city, :bv)");
$city = '.*ing.*';
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['CITY'] as $c) {
print $c . "<br>\n";
}
// Output is
// Beijing
// Singapore
oci_free_statement($stid);
oci_close($conn);
?>
For a small, fixed number of IN clause conditions, use individual bind variables. Values unknown at run time can be set to NULL. This allows a single statement to be used by all application users, maximizing Oracle DB cache efficiency.
Example #7 Binding Multiple Values in an IN Clause
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = 'SELECT last_name FROM employees WHERE employee_id in (:e1, :e2, :e3)';
$stid = oci_parse($conn, $sql);
$mye1 = 103;
$mye2 = 104;
$mye3 = NULL; // pretend we were not given this value
oci_bind_by_name($stid, ':e1', $mye1);
oci_bind_by_name($stid, ':e2', $mye2);
oci_bind_by_name($stid, ':e3', $mye3);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['LAST_NAME'] as $name) {
print $name ."<br>\n";
}
// Output is
// Ernst
// Hunold
oci_free_statement($stid);
oci_close($conn);
?>
Example #8 Binding a ROWID returned by a query
<?php
// Create the table with:
// CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
// INSERT INTO mytab (id, salary, name) VALUES (1, 100, 'Chris');
// COMMIT;
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT ROWID, name FROM mytab WHERE id = :id_bv FOR UPDATE');
$id = 1;
oci_bind_by_name($stid, ':id_bv', $id);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$rid = $row['ROWID'];
$name = $row['NAME'];
// Change name to upper case & save the changes
$name = strtoupper($name);
$stid = oci_parse($conn, 'UPDATE mytab SET name = :n_bv WHERE ROWID = :r_bv');
oci_bind_by_name($stid, ':n_bv', $name);
oci_bind_by_name($stid, ':r_bv', $rid, -1, OCI_B_ROWID);
oci_execute($stid);
// The table now contains 1, 100, CHRIS
oci_free_statement($stid);
oci_close($conn);
?>
Example #9 Binding a ROWID on INSERT
<?php
// This example inserts an id & name, and then updates the salary
// Create the table with:
// CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//
// Based on original ROWID example by thies at thieso dot net (980221)
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$sql = "INSERT INTO mytab (id, name) VALUES(:id_bv, :name_bv)
RETURNING ROWID INTO :rid";
$ins_stid = oci_parse($conn, $sql);
$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_bind_by_name($ins_stid, ":id_bv", $id, 10);
oci_bind_by_name($ins_stid, ":name_bv", $name, 32);
oci_bind_by_name($ins_stid, ":rid", $rowid, -1, OCI_B_ROWID);
$sql = "UPDATE mytab SET salary = :salary WHERE ROWID = :rid";
$upd_stid = oci_parse($conn, $sql);
oci_bind_by_name($upd_stid, ":rid", $rowid, -1, OCI_B_ROWID);
oci_bind_by_name($upd_stid, ":salary", $salary, 32);
// ids and names to insert
$data = array(1111 => "Larry",
2222 => "Bill",
3333 => "Jim");
// Salary of each person
$salary = 10000;
// Insert and immediately update each row
foreach ($data as $id => $name) {
oci_execute($ins_stid);
oci_execute($upd_stid);
}
$rowid->free();
oci_free_statement($upd_stid);
oci_free_statement($ins_stid);
// Show the new rows
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
var_dump($row);
}
oci_free_statement($stid);
oci_close($conn);
?>
Example #10 Binding for a PL/SQL stored function
<?php
// Before running the PHP program, create a stored function in
// SQL*Plus or SQL Developer:
//
// CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
// BEGIN
// RETURN p * 3;
// END;
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$p = 8;
$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);
// The return value is an OUT bind. The default type will be a string
// type so binding a length 40 means that at most 40 digits will be
// returned.
oci_bind_by_name($stid, ':r', $r, 40);
oci_execute($stid);
print "$r\n"; // prints 24
oci_free_statement($stid);
oci_close($conn);
?>
Example #11 Binding parameters for a PL/SQL stored procedure
<?php
// Before running the PHP program, create a stored procedure in
// SQL*Plus or SQL Developer:
//
// CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
// BEGIN
// p2 := p1 * 2;
// END;
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$p1 = 8;
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
// The second procedure parameter is an OUT bind. The default type
// will be a string type so binding a length 40 means that at most 40
// digits will be returned.
oci_bind_by_name($stid, ':p2', $p2, 40);
oci_execute($stid);
print "$p2\n"; // prints 16
oci_free_statement($stid);
oci_close($conn);
?>
Example #12 Binding a CLOB column
<?php
// Before running, create the table:
// CREATE TABLE mytab (mykey NUMBER, myclob CLOB);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$mykey = 12343; // arbitrary key for this example;
$sql = "INSERT INTO mytab (mykey, myclob)
VALUES (:mykey, EMPTY_CLOB())
RETURNING myclob INTO :myclob";
$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_DEFAULT);
$clob->save("A very long string");
oci_commit($conn);
// Fetching CLOB data
$query = 'SELECT myclob FROM mytab WHERE mykey = :mykey';
$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);
print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) {
print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
unset($row);
}
print '</table>';
?>
Example #13 Binding a PL/SQL BOOLEAN
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$plsql =
"begin
:output1 := true;
:output2 := false;
end;";
$s = oci_parse($c, $plsql);
oci_bind_by_name($s, ':output1', $output1, -1, OCI_B_BOL);
oci_bind_by_name($s, ':output2', $output2, -1, OCI_B_BOL);
oci_execute($s);
var_dump($output1); // true
var_dump($output2); // false
?>
Returns TRUE on success or FALSE on failure.
Do not use magic_quotes_gpc or addslashes() and oci_bind_by_name() simultaneously as no quoting is needed. Any magically applied quotes will be written into your database because oci_bind_by_name() inserts data verbatim and does not remove quotes or escape characters.
Note:
If you bind a string to a
CHARcolumn in aWHEREclause, remember that Oracle uses blank-padded comparison semantics forCHARcolumns. Your PHP variable should be blank padded to the same width as the column for theWHEREclause to succeed.
Note:
The PHP
variableargument is a reference. Some forms of loops do not work as expected:<?php
foreach ($myarray as $key => $value) {
oci_bind_by_name($stid, $key, $value);
}
?>This binds each key to the location of $value, so all bound variables end up pointing to the last loop iteration's value. Instead use the following:
<?php
foreach ($myarray as $key => $value) {
oci_bind_by_name($stid, $key, $myarray[$key]);
}
?>
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_cancel — Cancels reading from cursor
$statement
) : boolInvalidates a cursor, freeing all associated resources and cancels the ability to read from it.
statementAn OCI statement.
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.3.7, PHP 7, PECL OCI8 >= 1.4.6)
oci_client_version — Returns the Oracle client library version
Returns a string containing the version number of the Oracle C client library that PHP is linked with.
None
Returns the version number as a string.
Example #1 oci_client_version() example
<?php
echo "Client Version: " . oci_client_version(); // Client version: 11.2.0.2
?>
Note:
Oracle libraries before 10gR2 do not have the underlying functionality to get the client library version number. The string "Unknown" will be returned in this case.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_close — Closes an Oracle connection
$connection
) : bool
Unsets connection. The underlying database
connection is closed if no other resources are using it and if it
was created with oci_connect()
or oci_new_connect().
It is recommended to close connections that are no longer needed because this makes database resources available for other users.
connectionAn Oracle connection identifier returned by oci_connect(), oci_pconnect(), or oci_new_connect().
Returns TRUE on success or FALSE on failure.
Example #1 Closing a connection
Resources associated with a connection should be closed to ensure the underlying database connection is properly terminated and the database resources are released.
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM departments');
$r = oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);
// Free the statement identifier when closing the connection
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 Database connections are not closed until all references are closed
The internal refcount of a connection identifier must be zero before the underlying connection to the database is closed.
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM departments'); // this increases the refcount on $conn
oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);
oci_close($conn);
// $conn is no longer usable in the script but the underlying database
// connection is still held open until $stid is freed.
var_dump($conn); // prints NULL
// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user is still connected.
sleep(10);
// When $stid is freed, the database connection is physically closed
oci_free_statement($stid);
// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user has disconnected.
sleep(10);
?>
Example #3 Closing a connection opened more than once
When database credentials are reused, both connections must be closed before the underlying database connection is closed.
<?php
$conn1 = oci_connect('hr', 'welcome', 'localhost/XE');
// Using the same credentials reuses the same underlying database connection
// Any uncommitted changes done on $conn1 will be visible in $conn2
$conn2 = oci_connect('hr', 'welcome', 'localhost/XE');
// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that only one database user is connected.
sleep(10);
oci_close($conn1); // doesn't close the underlying database connection
var_dump($conn1); // prints NULL because the variable $conn1 is no longer usable
var_dump($conn2); // displays that $conn2 is still a valid connection resource
?>
Example #4 Connections are closed when variables go out of scope
When all variables referencing a connection go out of scope and are freed by PHP, a rollback occurs (if necessary) and the underlying connection to the database is closed.
<?php
function myfunc() {
$conn = oci_connect('hr', 'hrpwd', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'UPDATE mytab SET id = 100');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
return "Finished";
}
$r = myfunc();
// At this point a rollback occurred and the underlying database connection was released.
print $r; // displays the function return value "Finished"
?>
Note:
Variables that have a dependency on the connection identifier, such as statement identifiers returned by oci_parse(), must also be freed before the underlying database connection is closed.
Note:
Prior to version PHP 5.1.2 (PECL OCI8 1.1) oci_close() was a no-op. In more recent versions it correctly closes the Oracle connection. Use oci8.old_oci_close_semantics option to restore old behavior of this function.
Note:
The oci_close() function does not close the underlying database connections created with oci_pconnect().
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_commit — Commits the outstanding database transaction
$connection
) : bool
Commits the outstanding transaction for the
Oracle connection. A commit ends the
current transaction and makes permanent all changes. It releases
all locks held.
A transaction begins when the first SQL statement that changes data
is executed with oci_execute() using
the OCI_NO_AUTO_COMMIT flag. Further data
changes made by other statements become part of the same
transaction. Data changes made in a transaction are temporary
until the transaction is committed or rolled back. Other users of
the database will not see the changes until they are committed.
When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.
connectionAn Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().
Returns TRUE on success or FALSE on failure.
Example #1 oci_commit() example
<?php
// Insert into several tables, rolling back the changes if an error occurs
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1. The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
oci_rollback($conn); // rollback changes to both tables
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
// Commit the changes to both tables
$r = oci_commit($conn);
if (!$r) {
$e = oci_error($conn);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>
Note:
Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.
Any call to oci_execute() that uses
OCI_COMMIT_ON_SUCCESSmode explicitly or by default will commit any previous uncommitted transaction.Any Oracle DDL statement such as
CREATEorDROPwill automatically commit any uncommitted transaction.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_connect — Connect to an Oracle database
$username
, string $password
[, string $connection_string
[, string $character_set
[, int $session_mode
]]] ) : resourceReturns a connection identifier needed for most other OCI8 operations.
See Connection Handling for general information on connection management and connection pooling.
From PHP 5.1.2 (PECL OCI8 1.1) oci_close() can be used to close the connection.
The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call. This means that transactions in one handle are also in the other handles, because they use the same underlying database connection. If two handles need to be transactionally isolated from each other, use oci_new_connect() instead.
usernameThe Oracle user name.
password
The password for username.
connection_stringContains
the Oracle instance to connect to. It can be
an » Easy Connect
string, or a Connect Name from
the tnsnames.ora file, or the name of a local
Oracle instance.
If not specified, PHP uses
environment variables such as TWO_TASK (on Linux)
or LOCAL (on Windows)
and ORACLE_SID to determine the
Oracle instance to connect to.
To use the Easy Connect naming method, PHP must be linked with Oracle
10g or greater Client libraries. The Easy Connect string for Oracle
10g is of the form:
[//]host_name[:port][/service_name]. From Oracle
11g, the syntax is:
[//]host_name[:port][/service_name][:server_type][/instance_name].
Service names can be found by running the Oracle
utility lsnrctl status on the database server
machine.
The tnsnames.ora file can be in the Oracle Net
search path, which
includes $ORACLE_HOME/network/admin
and /etc. Alternatively
set TNS_ADMIN so
that $TNS_ADMIN/tnsnames.ora is read. Make sure
the web daemon has read access to the file.
character_setDetermines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.
If not specified, the
Oracle Client libraries determine a character set from
the NLS_LANG environment variable.
Passing this parameter can reduce the time taken to connect.
session_modeThis
parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the
following values: OCI_DEFAULT,
OCI_SYSOPER and OCI_SYSDBA.
If either OCI_SYSOPER or
OCI_SYSDBA were specified, this function will try
to establish privileged connection using external credentials.
Privileged connections are disabled by default. To enable them you
need to set oci8.privileged_connect
to On.
PHP 5.3 (PECL OCI8 1.3.4) introduced the
OCI_CRED_EXT mode value. This tells Oracle to use
External or OS authentication, which must be configured in the
database. The OCI_CRED_EXT flag can only be used
with username of "/" and a empty password.
oci8.privileged_connect
may be On or Off.
OCI_CRED_EXT may be combined with the
OCI_SYSOPER or
OCI_SYSDBA modes.
OCI_CRED_EXT is not supported on Windows for
security reasons.
Returns a connection identifier or FALSE on error.
Example #1 Basic oci_connect() using Easy Connect syntax
<?php
// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
Example #2 Basic oci_connect() using a Network Connect name
<?php
// Connects to the MYDB database described in tnsnames.ora file,
// One example tnsnames.ora entry for MYDB could be:
// MYDB =
// (DESCRIPTION =
// (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.oracle.com)(PORT = 1521))
// (CONNECT_DATA =
// (SERVER = DEDICATED)
// (SERVICE_NAME = XE)
// )
// )
$conn = oci_connect('hr', 'welcome', 'MYDB');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
Example #3 oci_connect() with an explicit character set
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
Example #4 Using multiple calls to oci_connect()
<?php
$c1 = oci_connect("hr", "welcome", 'localhost/XE');
$c2 = oci_connect("hr", "welcome", 'localhost/XE');
// Both $c1 and $c2 show the same PHP resource id meaning they use the
// same underlying database connection
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";
function create_table($conn)
{
$stmt = oci_parse($conn, "create table hallo (test varchar2(64))");
oci_execute($stmt);
echo "Created table<br>\n";
}
function drop_table($conn)
{
$stmt = oci_parse($conn, "drop table hallo");
oci_execute($stmt);
echo "Dropped table<br>\n";
}
function insert_data($connname, $conn)
{
$stmt = oci_parse($conn, "insert into hallo
values(to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
oci_execute($stmt, OCI_DEFAULT);
echo "$connname inserted row without committing<br>\n";
}
function rollback($connname, $conn)
{
oci_rollback($conn);
echo "$connname rollback<br>\n";
}
function select_data($connname, $conn)
{
$stmt = oci_parse($conn, "select * from hallo");
oci_execute($stmt, OCI_DEFAULT);
echo "$connname ----selecting<br>\n";
while (oci_fetch($stmt)) {
echo " " . oci_result($stmt, "TEST") . "<br>\n";
}
echo "$connname ----done<br>\n";
}
create_table($c1);
insert_data('c1', $c1); // Insert a row using c1
sleep(2); // sleep to show a different timestamp for the 2nd row
insert_data('c2', $c2); // Insert a row using c2
select_data('c1', $c1); // Results of both inserts are returned
select_data('c2', $c2); // Results of both inserts are returned
rollback('c1', $c1); // Rollback using c1
select_data('c1', $c1); // Both inserts have been rolled back
select_data('c2', $c2);
drop_table($c1);
// Closing one of the connections makes the PHP variable unusable, but
// the other could be used
oci_close($c1);
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";
// Output is:
// c1 is Resource id #5
// c2 is Resource id #5
// Created table
// c1 inserted row without committing
// c2 inserted row without committing
// c1 ----selecting
// 09-DEC-09 12:14:43
// 09-DEC-09 12:14:45
// c1 ----done
// c2 ----selecting
// 09-DEC-09 12:14:43
// 09-DEC-09 12:14:45
// c2 ----done
// c1 rollback
// c1 ----selecting
// c1 ----done
// c2 ----selecting
// c2 ----done
// Dropped table
// c1 is
// c2 is Resource id #5
?>
Note:
An incorrectly installed or configured OCI8 extension will often manifest itself as a connection problem or error. See Installing/Configuring for troubleshooting information.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_define_by_name — Associates a PHP variable with a column for query fetches
$statement
, string $column_name
, mixed &$variable
[, int $type = SQLT_CHR
] ) : boolAssociates a PHP variable with a column for query fetches using oci_fetch().
The oci_define_by_name() call must occur before executing oci_execute().
statementA valid OCI8 statement
identifier created by oci_parse() and executed
by oci_execute(), or a REF
CURSOR statement identifier.
column_nameThe column name used in the query.
Use uppercase for Oracle's default, non-case sensitive column names. Use the exact column name case for case-sensitive column names.
variableThe PHP variable that will contain the returned column value.
type
The data type to be returned. Generally not needed. Note that
Oracle-style data conversions are not performed. For example,
SQLT_INT will be ignored and the returned
data type will still be SQLT_CHR.
You can optionally use oci_new_descriptor() to allocate LOB/ROWID/BFILE descriptors.
Returns TRUE on success or FALSE on failure.
Example #1 oci_define_by_name() example
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);
oci_execute($stid);
// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
echo "Location id $locid is $city<br>\n";
}
// Displays:
// Location id 1000 is Roma
// Location id 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_define_by_name() with case sensitive column names
<?php
/*
Before running, create the table with a case sensitive column name:
CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM mytab');
// Use uppercase for non case-sensitive column names
oci_define_by_name($stid, 'ID', $id);
// Use the exact case for case-sensitive column names
oci_define_by_name($stid, 'MyDescription', $mydesc);
oci_execute($stid);
while (oci_fetch($stid)) {
echo "id $id is $mydesc<br>\n";
}
// Displays:
// id 1 is Iced Coffee
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 oci_define_by_name() with LOB columns
<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, fruit CLOB);
INSERT INTO mytab (id, fruit) values (1, 'apple');
INSERT INTO mytab (id, fruit) values (2, 'orange');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM mytab');
// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);
oci_define_by_name($stid, 'FRUIT', $fruit); // $fruit will become a LOB descriptor
oci_execute($stid);
while (oci_fetch($stid)) {
echo $id . " is " . $fruit->load(100) . "<br>\n";
}
// Displays:
// 1 is apple
// 2 is orange
$fruit->free();
oci_free_statement($stid);
oci_close($conn);
?>
Example #4 oci_define_by_name() with an explicit type
<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, fruit CLOB);
INSERT INTO mytab (id, fruit) values (1, 'apple');
INSERT INTO mytab (id, fruit) values (2, 'orange');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM mytab');
// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);
$fruit = oci_new_descriptor($conn, OCI_D_LOB);
oci_define_by_name($stid, 'FRUIT', $fruit, OCI_D_CLOB);
oci_execute($stid);
while (oci_fetch($stid)) {
echo $id . " is " . $fruit->load(100) . "<br>\n";
}
// Displays:
// 1 is apple
// 2 is orange
$fruit->free();
oci_free_statement($stid);
oci_close($conn);
?>
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_error — Returns the last error found
$resource
] ) : arrayReturns the last error found.
The function should be called immediately after an error occurs. Errors are cleared by a successful statement.
resource
For most errors, resource is the
resource handle that was passed to the failing function call.
For connection errors with oci_connect(),
oci_new_connect() or
oci_pconnect() do not pass resource.
If no error is found, oci_error() returns
FALSE. Otherwise, oci_error() returns the
error information as an associative array.
| Array key | Type | Description |
|---|---|---|
code |
integer | The Oracle error number. |
message |
string | The Oracle error text. |
offset |
integer |
The byte position of an error in the SQL statement. If there
was no statement, this is 0
|
sqltext |
string | The SQL statement text. If there was no statement, this is an empty string. |
Example #1 Displaying the Oracle error message after a connection error
<?php
$conn = oci_connect("hr", "welcome", "localhost/XE");
if (!$conn) {
$e = oci_error(); // For oci_connect errors do not pass a handle
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>
Example #2 Displaying the Oracle error message after a parsing error
<?php
$stid = oci_parse($conn, "select ' from dual"); // note mismatched quote
if (!$stid) {
$e = oci_error($conn); // For oci_parse errors pass the connection handle
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>
Example #3 Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error
<?php
$stid = oci_parse($conn, "select does_not_exist from dual");
$r = oci_execute($stid);
if (!$r) {
$e = oci_error($stid); // For oci_execute errors pass the statement handle
print htmlentities($e['message']);
print "\n<pre>\n";
print htmlentities($e['sqltext']);
printf("\n%".($e['offset']+1)."s", "^");
print "\n</pre>\n";
}
?>
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_execute — Executes a statement
$statement
[, int $mode = OCI_COMMIT_ON_SUCCESS
] ) : bool
Executes a statement previously returned
from oci_parse().
After execution, statements like INSERT will
have data committed to the database by default. For statements
like SELECT, execution performs the logic of the
query. Query results can subsequently be fetched in PHP with
functions like oci_fetch_array().
Each parsed statement may be executed multiple times, saving the
cost of re-parsing. This is commonly used
for INSERT statements when data is bound
with oci_bind_by_name().
statementA valid OCI statement identifier.
modeAn optional second parameter can be one of the following constants:
| Constant | Description |
|---|---|
OCI_COMMIT_ON_SUCCESS |
Automatically commit all outstanding changes for this connection when the statement has succeeded. This is the default. |
OCI_DESCRIBE_ONLY |
Make query meta data available to functions like oci_field_name() but do not create a result set. Any subsequent fetch call such as oci_fetch_array() will fail. |
OCI_NO_AUTO_COMMIT |
Do not automatically commit changes. Prior to PHP
5.3.2 (PECL OCI8 1.4)
use OCI_DEFAULT which is equivalent
to OCI_NO_AUTO_COMMIT. |
Using OCI_NO_AUTO_COMMIT mode starts or continues a
transaction. Transactions are automatically rolled back when
the connection is closed, or when the script ends. Explicitly
call oci_commit() to commit a transaction,
or oci_rollback() to abort it.
When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.
If OCI_NO_AUTO_COMMIT mode is used for any
statement including queries, and
oci_commit()
or oci_rollback() is not subsequently
called, then OCI8 will perform a rollback at the end of the
script even if no data was changed. To avoid an unnecessary
rollback, many scripts do not
use OCI_NO_AUTO_COMMIT mode for queries or
PL/SQL. Be careful to ensure the appropriate transactional
consistency for the application when
using oci_execute() with different modes in
the same script.
Returns TRUE on success or FALSE on failure.
Example #1 oci_execute() for queries
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
Example #2 oci_execute() without specifying a mode example
<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (col1 NUMBER);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');
oci_execute($stid); // The row is committed and immediately visible to other users
?>
Example #3 oci_execute() with OCI_NO_AUTO_COMMIT example
<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (col1 NUMBER);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $i, 10);
for ($i = 1; $i <= 5; ++$i) {
oci_execute($stid, OCI_NO_AUTO_COMMIT); // use OCI_DEFAULT for PHP <= 5.3.1
}
oci_commit($conn); // commits all new values: 1, 2, 3, 4, 5
?>
Example #4 oci_execute() with different commit modes example
<?php
// Before running, create the table:
// CREATE TABLE MYTABLE (col1 NUMBER);
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');
oci_execute($stid, OCI_NO_AUTO_COMMIT); // data not committed
$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (456)');
oci_execute($stid); // commits both 123 and 456 values
?>
Example #5 oci_execute() with
OCI_DESCRIBE_ONLY example
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM locations');
oci_execute($s, OCI_DESCRIBE_ONLY);
for ($i = 1; $i <= oci_num_fields($stid); ++$i) {
echo oci_field_name($stid, $i) . "<br>\n";
}
?>
Note:
Transactions are automatically rolled back when connections are closed, or when the script ends, whichever is soonest. Explicitly call oci_commit() to commit a transaction.
Any call to oci_execute() that uses
OCI_COMMIT_ON_SUCCESSmode explicitly or by default will commit any previous uncommitted transaction.Any Oracle DDL statement such as
CREATEorDROPwill automatically commit any uncommitted transaction.
Note:
Because the oci_execute() function generally sends the statement to the database, oci_execute() can identify some statement syntax errors that the lightweight, local oci_parse() function does not.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array
$statement
, array &$output
[, int $skip = 0
[, int $maxrows = -1
[, int $flags = OCI_FETCHSTATEMENT_BY_COLUMN + OCI_ASSOC
]]] ) : intFetches multiple rows from a query into a two-dimensional array. By default, all rows are returned.
This function can be called only once for each query executed with oci_execute().
statementA valid OCI8 statement
identifier created by oci_parse() and executed
by oci_execute(), or a REF
CURSOR statement identifier.
outputThe variable to contain the returned rows.
LOB columns are returned as strings, where Oracle supports conversion.
See oci_fetch_array() for more information on how data and types are fetched.
skipThe number of initial rows to discard when fetching the result. The default value is 0, so the first row onwards is returned.
maxrows
The number of rows to return. The default is -1 meaning return
all the rows from skip + 1 onwards.
flags
Parameter flags indicates the array
structure and whether associative arrays should be used.
| Constant | Description |
|---|---|
OCI_FETCHSTATEMENT_BY_ROW |
The outer array will contain one sub-array per query row. |
OCI_FETCHSTATEMENT_BY_COLUMN |
The outer array will contain one sub-array per query column. This is the default. |
Arrays can be indexed either by column heading or numerically. Only one index mode will be returned.
| Constant | Description |
|---|---|
OCI_NUM |
Numeric indexes are used for each column's array. |
OCI_ASSOC |
Associative indexes are used for each column's array. This is the default. |
Use the addition operator "+" to choose a combination of array structure and index modes.
Oracle's default, non-case sensitive column names will have
uppercase array keys. Case-sensitive column names will have
array keys using the exact column case.
Use var_dump()
on output to verify the appropriate case
to use for each query.
Queries that have more than one column with the same name should use column aliases. Otherwise only one of the columns will appear in an associative array.
Returns the number of rows in output, which
may be 0 or more, or FALSE on failure.
Example #1 oci_fetch_all() example
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);
$nrows = oci_fetch_all($stid, $res);
echo "$nrows rows fetched<br>\n";
var_dump($res);
// var_dump output is:
// 2 rows fetched
// array(2) {
// ["POSTAL_CODE"]=>
// array(2) {
// [0]=>
// string(6) "00989x"
// [1]=>
// string(6) "10934x"
// }
// ["CITY"]=>
// array(2) {
// [0]=>
// string(4) "Roma"
// [1]=>
// string(6) "Venice"
// }
// }
// Pretty-print the results
echo "<table border='1'>\n";
foreach ($res as $col) {
echo "<tr>\n";
foreach ($col as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_fetch_all() example with OCI_FETCHSTATEMENT_BY_ROW
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);
$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);
echo "$nrows rows fetched<br>\n";
var_dump($res);
// Output is:
// 2 rows fetched
// array(2) {
// [0]=>
// array(2) {
// ["POSTAL_CODE"]=>
// string(6) "00989x"
// ["CITY"]=>
// string(4) "Roma"
// }
// [1]=>
// array(2) {
// ["POSTAL_CODE"]=>
// string(6) "10934x"
// ["CITY"]=>
// string(6) "Venice"
// }
// }
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 oci_fetch_all() with OCI_NUM
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);
$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_NUM);
echo "$nrows rows fetched<br>\n";
var_dump($res);
// Output is:
// 2 rows fetched
// array(2) {
// [0]=>
// array(2) {
// [0]=>
// string(6) "00989x"
// [1]=>
// string(4) "Roma"
// }
// [1]=>
// array(2) {
// [0]=>
// string(6) "10934x"
// [1]=>
// string(6) "Venice"
// }
// }
oci_free_statement($stid);
oci_close($conn);
?>
Note:
Using
skipis very inefficient. All the rows to be skipped are included in the result set that is returned from the database to PHP. They are then discarded. It is more efficient to use SQL to restrict the offset and range of rows in the query. See oci_fetch_array() for an example.
Note:
Queries that return a large number of rows can be more memory efficient if a single-row fetching function like oci_fetch_array() is used.
Note:
For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().
Note:
Will not return rows from Oracle Database 12c Implicit Result Sets. Use oci_fetch_array() instead.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_fetch_array — Returns the next row from a query as an associative or numeric array
$statement
[, int $mode
] ) : array
Returns an array containing the next result-set row of a query.
Each array entry corresponds to a column of the row. This function
is typically called in a loop until it returns FALSE, indicating
no more rows exist.
If statement corresponds to a PL/SQL block
returning Oracle Database 12c Implicit Result Sets, then rows from
all sets are consecutively fetched. If
statement is returned
by oci_get_implicit_resultset(), then only the
subset of rows for one child query are returned.
For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver
statementA valid OCI8 statement
identifier created by oci_parse() and executed
by oci_execute(), or a REF
CURSOR statement identifier.
Can also be a statement identifier returned by oci_get_implicit_resultset().
modeAn optional second parameter can be any combination of the following constants:
| Constant | Description |
|---|---|
OCI_BOTH |
Returns an array with both associative and numeric
indices. This is the same
as OCI_ASSOC
+ OCI_NUM and is the default
behavior. |
OCI_ASSOC |
Returns an associative array. |
OCI_NUM |
Returns a numeric array. |
OCI_RETURN_NULLS |
Creates elements for NULL fields. The element
values will be a PHP NULL.
|
OCI_RETURN_LOBS |
Returns the contents of LOBs instead of the LOB descriptors. |
The default mode is OCI_BOTH.
Use the addition operator "+" to specify more than one mode at a time.
Returns an array with associative and/or numeric indices. If there
are no more rows in the statement then
FALSE is returned.
By default, LOB columns are returned as LOB descriptors.
DATE columns are returned as strings formatted
to the current date format. The default format can be changed with
Oracle environment variables such as NLS_LANG or
by a previously executed ALTER SESSION SET
NLS_DATE_FORMAT command.
Oracle's default, non-case sensitive column names will have uppercase associative indices in the result array. Case-sensitive column names will have array indices using the exact column case. Use var_dump() on the result array to verify the appropriate case to use for each query.
The table name is not included in the array index. If your query
contains two different columns with the same name,
use OCI_NUM or add a column alias to the query
to ensure name uniqueness, see example #7. Otherwise only one
column will be returned via PHP.
Example #1 oci_fetch_array() with OCI_BOTH
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH)) != false) {
// Use the uppercase column names for the associative array indices
echo $row[0] . " and " . $row['DEPARTMENT_ID'] . " are the same<br>\n";
echo $row[1] . " and " . $row['DEPARTMENT_NAME'] . " are the same<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_fetch_array() with OCI_NUM
<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_NUM)) != false) {
echo $row[0] . "<br>\n";
echo $row[1]->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}
// Output is:
// 1
// A very long
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 oci_fetch_array() with OCI_ASSOC
<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['ID'] . "<br>\n";
echo $row['DESCRIPTION']->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}
// Output is:
// 1
// A very long
oci_free_statement($stid);
oci_close($conn);
?>
Example #4 oci_fetch_array() with OCI_RETURN_NULLS
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC)) != false) { // Ignore NULLs
var_dump($row);
}
/*
The above code prints:
array(1) {
[1]=>
string(1) "1"
}
*/
$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) { // Fetch NULLs
var_dump($row);
}
/*
The above code prints:
array(2) {
[1]=>
string(1) "1"
["NULL"]=>
NULL
}
*/
?>
Example #5 oci_fetch_array() with OCI_RETURN_LOBS
<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) != false) {
echo $row['ID'] . "<br>\n";
echo $row['DESCRIPTION'] . "<br>\n"; // this contains all of DESCRIPTION
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
unset($row);
}
// Output is:
// 1
// A very long string
oci_free_statement($stid);
oci_close($conn);
?>
Example #6 oci_fetch_array() with case sensitive column names
<?php
/*
Before running, create the table:
CREATE TABLE mytab ("Name" VARCHAR2(20), city VARCHAR2(20));
INSERT INTO mytab ("Name", city) values ('Chris', 'Melbourne');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
// Because 'Name' was created as a case-sensitive column, that same
// case is used for the array index. However uppercase 'CITY' must
// be used for the case-insensitive column index
print $row['Name'] . "<br>\n"; // prints Chris
print $row['CITY'] . "<br>\n"; // prints Melbourne
oci_free_statement($stid);
oci_close($conn);
?>
Example #7 oci_fetch_array() with columns having duplicate names
<?php
/*
Before running, create the tables:
CREATE TABLE mycity (id NUMBER, name VARCHAR2(20));
INSERT INTO mycity (id, name) values (1, 'Melbourne');
CREATE TABLE mycountry (id NUMBER, name VARCHAR2(20));
INSERT INTO mycountry (id, name) values (1, 'Australia');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT mycity.name, mycountry.name
FROM mycity, mycountry
WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);
// Output only contains one "NAME" entry:
// array(1) {
// ["NAME"]=>
// string(9) "Australia"
// }
// To query a repeated column name, use an SQL column alias like "AS ctnm":
$sql = 'SELECT mycity.name AS ctnm, mycountry.name
FROM mycity, mycountry
WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);
// Output now contains both columns selected:
// array(2) {
// ["CTNM"]=>
// string(9) "Melbourne"
// ["NAME"]=>
// string(9) "Australia"
// }
oci_free_statement($stid);
oci_close($conn);
?>
Example #8 oci_fetch_array() with DATE columns
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Set the date format for this connection.
// For performance reasons, consider changing the format
// in a trigger or with environment variables instead
$stid = oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
oci_execute($stid);
$stid = oci_parse($conn, 'SELECT hire_date FROM employees WHERE employee_id = 188');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
echo $row['HIRE_DATE'] . "<br>\n"; // prints 1997-06-14
oci_free_statement($stid);
oci_close($conn);
?>
Example #9 oci_fetch_array() with REF CURSOR
<?php
/*
Create the PL/SQL stored procedure as:
CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
BEGIN
OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);
// Execute the returned REF CURSOR and fetch from it like a statement identifier
oci_execute($refcur);
echo "<table border='1'>\n";
while (($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : " ")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);
?>
Example #10 Pagination with oci_fetch_array() using a LIMIT-like query
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Find the version of the database
preg_match('/Release ([0-9]+)\./', oci_server_version($conn), $matches);
$oracleversion = $matches[1];
// This is the query you want to "page" through
$sql = 'SELECT city, postal_code FROM locations ORDER BY city';
if ($oracleversion >= 12) {
// Make use of Oracle 12c OFFSET / FETCH NEXT syntax
$sql = $sql . ' OFFSET :offset ROWS FETCH NEXT :numrows ROWS ONLY';
} else {
// Older Oracle versions need a nested query selecting a subset
// from $sql. Or, if the SQL statement is known at development
// time, consider using a row_number() function instead of this
// nested solution. In production environments, be careful to
// avoid SQL Injection issues with concatenation.
$sql = "SELECT * FROM (SELECT a.*, ROWNUM AS my_rnum
FROM ($sql) a
WHERE ROWNUM <= :offset + :numrows)
WHERE my_rnum > :offset";
}
$offset = 0; // skip this many rows
$numrows = 5; // return 5 rows
$stid = oci_parse($conn, $sql);
oci_bind_by_name($stid, ':numrows', $numrows);
oci_bind_by_name($stid, ':offset', $offset);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) != false) {
echo $row['CITY'] . " " . $row['POSTAL_CODE'] . "<br>\n";
}
// Output is:
// Beijing 190518
// Bern 3095
// Bombay 490231
// Geneva 1730
// Hiroshima 6823
oci_free_statement($stid);
oci_close($conn);
?>
Example #11 oci_fetch_array() with Oracle Database 12c Implicit Result Sets
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// Requires OCI8 2.0 and Oracle Database 12c
// Also see oci_get_implicit_resultset()
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):" ")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
// Output is:
// Beijing 190518
// Bern 3095
// Bombay 490231
// CN
// CH
// IN
oci_free_statement($stid);
oci_close($conn);
?>
Note:
Associative array indices need to be in uppercase for standard Oracle columns that were created with case insensitive names.
Note:
For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().
Note:
The function oci_fetch_array() is insignificantly slower than oci_fetch_assoc() or oci_fetch_row(), but is more flexible.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_fetch_assoc — Returns the next row from a query as an associative array
$statement
) : array
Returns an associative array containing the next result-set row of a query.
Each array entry corresponds to a column of the row. This function
is typically called in a loop until it returns FALSE, indicating
no more rows exist.
Calling oci_fetch_assoc() is identical to
calling oci_fetch_array()
with OCI_ASSOC
+ OCI_RETURN_NULLS.
statementA valid OCI8 statement
identifier created by oci_parse() and executed
by oci_execute(), or a REF
CURSOR statement identifier.
Returns an associative array. If there are no more rows in
the statement then FALSE is returned.
Example #1 oci_fetch_assoc() Example
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);
while (($row = oci_fetch_assoc($stid)) != false) {
echo $row['DEPARTMENT_ID'] . " " . $row['DEPARTMENT_NAME'] . "<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Note:
See oci_fetch_array() for more examples of fetching rows.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_fetch_object — Returns the next row from a query as an object
$statement
) : object
Returns an object containing the next result-set row of a query.
Each attribute of the object corresponds to a column of the row.
This function is typically called in a loop until it returns
FALSE, indicating no more rows exist.
For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver
statementA valid OCI8 statement
identifier created by oci_parse() and executed
by oci_execute(), or a REF
CURSOR statement identifier.
Returns an object. Each attribute of the object corresponds to a
column of the row. If there are no more rows in
the statement then FALSE is returned.
Any LOB columns are returned as LOB descriptors.
DATE columns are returned as strings formatted
to the current date format. The default format can be changed with
Oracle environment variables such as NLS_LANG or
by a previously executed ALTER SESSION SET
NLS_DATE_FORMAT command.
Oracle's default, non-case sensitive column names will have uppercase attribute names. Case-sensitive column names will have attribute names using the exact column case. Use var_dump() on the result object to verify the appropriate case for attribute access.
Attribute values will be NULL for any NULL
data fields.
Example #1 oci_fetch_object() example
<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description VARCHAR2(30));
INSERT INTO mytab (id, description) values (1, 'Fish and Chips');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_object($stid)) != false) {
// Use upper case attribute names for each standard Oracle column
echo $row->ID . "<br>\n";
echo $row->DESCRIPTION . "<br>\n";
}
// Output is:
// 1
// Fish and Chips
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_fetch_object() with case sensitive column names
<?php
/*
Before running, create the table with a case sensitive column name:
CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, "MyDescription" FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_object($stid)) != false) {
// Use upper case attribute names for each standard Oracle column
echo $row->ID . "<br>\n";
// Use the exact case for the case sensitive column name
echo $row->MyDescription . "<br>\n";
}
// Output is:
// 1
// Iced Coffee
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 oci_fetch_object() with LOBs
<?php
/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);
while (($row = oci_fetch_object($stid)) != false) {
echo $row->ID . "<br>\n";
// The following will output the first 11 bytes from DESCRIPTION
echo $row->DESCRIPTION->read(11) . "<br>\n";
}
// Output is:
// 1
// A very long
oci_free_statement($stid);
oci_close($conn);
?>
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_fetch_row — Returns the next row from a query as a numeric array
$statement
) : array
Returns a numerically indexed array containing the next result-set row of a query.
Each array entry corresponds to a column of the row. This function
is typically called in a loop until it returns FALSE, indicating
no more rows exist.
Calling oci_fetch_row() is identical to calling
oci_fetch_array()
with OCI_NUM
+ OCI_RETURN_NULLS.
statementA valid OCI8 statement
identifier created by oci_parse() and executed
by oci_execute(), or a REF
CURSOR statement identifier.
Returns a numerically indexed array. If there are no more rows in
the statement then FALSE is returned.
Example #1 oci_fetch_row() Example
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);
while (($row = oci_fetch_row($stid)) != false) {
echo $row[0] . " " . $row[1] . "<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Note:
See oci_fetch_array() for more examples of fetching rows.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_fetch — Fetches the next row from a query into internal buffers
$statement
) : boolFetches the next row from a query into internal buffers accessible either with oci_result(), or by using variables previously defined with oci_define_by_name().
See oci_fetch_array() for general information about fetching data.
statementA valid OCI8 statement
identifier created by oci_parse() and executed
by oci_execute(), or a REF
CURSOR statement identifier.
Returns TRUE on success or FALSE if there are no more rows in the
statement.
Example #1 oci_fetch() with defined variables
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);
oci_execute($stid);
// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
echo "Location id $locid is $city<br>\n";
}
// Displays:
// Location id 1000 is Roma
// Location id 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 oci_fetch() with oci_result()
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (oci_fetch($stid)) {
echo oci_result($stid, 'LOCATION_ID') . " is ";
echo oci_result($stid, 'CITY') . "<br>\n";
}
// Displays:
// 1000 is Roma
// 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>
Note:
Will not return rows from Oracle Database 12c Implicit Result Sets. Use oci_fetch_array() instead.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_field_is_null — Checks if a field in the currently fetched row is NULL
Checks if the given field from the current row of
statement is NULL.
statementA valid OCI statement identifier.
fieldCan be the field's index (1-based) or name.
Returns TRUE if field is NULL, FALSE otherwise.
Example #1 oci_field_name() example
<?php
// Create the table with:
// CREATE TABLE mytab (c1 NUMBER);
// INSERT INTO mytab VALUES (1);
// INSERT INTO mytab VALUES (NULL);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_RETURN_NULLS)) != false) {
$ncols = oci_num_fields($stid);
for ($col = 1; $col <= $ncols; $col++) {
var_dump(oci_field_is_null($stid, $col));
}
}
// Outputs:
// bool(false)
// bool(true)
oci_free_statement($stid);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_field_name — Returns the name of a field from the statement
Returns the name of the field.
statementA valid OCI statement identifier.
fieldCan be the field's index (1-based) or name.
Returns the name as a string, or FALSE on errors.
Example #1 oci_field_name() example
<?php
// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
// clob_col CLOB, date_col DATE);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
$column_type = oci_field_type($stid, $i);
echo "<tr>";
echo "<td>$column_name</td>";
echo "<td>$column_type</td>";
echo "</tr>\n";
}
echo "</table>\n";
// Outputs:
// Name Type
// NUMBER_COL NUMBER
// VARCHAR2_COL VARCHAR2
// CLOB_COL CLOB
// DATE_COL DATE
oci_free_statement($stid);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ocicolumnname() instead. This name still can be used, it was left as alias of oci_field_name() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_field_precision — Tell the precision of a field
Returns precision of the field.
For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).
statementA valid OCI statement identifier.
fieldCan be the field's index (1-based) or name.
Returns the precision as an integer, or FALSE on errors.
Example #1 oci_field_precision() Example
<?php
// Create the table with:
// CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
echo oci_field_name($stid, $i) . " "
. oci_field_precision($stid, $i) . " "
. oci_field_scale($stid, $i) . "<br>\n";
}
// Outputs:
// C1 0 -127
// C2 126 -127
// C3 4 0
// C4 5 3
oci_free_statement($stid);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_field_scale — Tell the scale of the field
Returns the scale of the column with field index.
For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).
statementA valid OCI statement identifier.
fieldCan be the field's index (1-based) or name.
Returns the scale as an integer, or FALSE on errors.
Example #1 oci_field_scale() Example
<?php
// Create the table with:
// CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
echo oci_field_name($stid, $i) . " "
. oci_field_precision($stid, $i) . " "
. oci_field_scale($stid, $i) . "<br>\n";
}
// Outputs:
// C1 0 -127
// C2 126 -127
// C3 4 0
// C4 5 3
oci_free_statement($stid);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_field_size — Returns field's size
Returns the size of a field.
statementA valid OCI statement identifier.
fieldCan be the field's index (1-based) or name.
Returns the size of a field in bytes, or FALSE on
errors.
Example #1 oci_field_size() example
<?php
// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
// clob_col CLOB, date_col DATE);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
$column_type = oci_field_type($stid, $i);
$column_size = oci_field_size($stid, $i);
echo "<tr>";
echo "<td>$column_name</td>";
echo "<td>$column_type</td>";
echo "<td>$column_size</td>";
echo "</tr>\n";
}
echo "</table>\n";
// Outputs:
// Name Type Length
// NUMBER_COL NUMBER 22
// VARCHAR2_COL VARCHAR2 1
// CLOB_COL CLOB 4000
// DATE_COL DATE 7
oci_free_statement($stid);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This name still can be used, it was left as alias of oci_field_size() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_field_type_raw — Tell the raw Oracle data type of the field
Returns Oracle's raw "SQLT" data type of the field.
If you want a field's type name, then use oci_field_type() instead.
statementA valid OCI statement identifier.
fieldCan be the field's index (1-based) or name.
Returns Oracle's raw data type as a number, or FALSE on errors.
Example #1 oci_field_type_raw() Example
<?php
// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1), clob_col CLOB, date_col DATE);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
$n = oci_num_fields($stid);
for ($i = 1; $i <= $n; ++$i) {
echo oci_field_name($stid, $i) . " is raw type: " . oci_field_type_raw($stid, $i) . "<br>\n";
}
// Output is:
// NUMBER_COL is raw type: 2
// VARCHAR2_COL is raw type: 1
// CLOB_COL is raw type: 112
// DATE_COL is raw type: 12
oci_free_statement($stid);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_field_type — Returns a field's data type name
Returns a field's data type name.
statementA valid OCI statement identifier.
fieldCan be the field's index (1-based) or name.
Returns the field data type as a string, or FALSE on errors.
Example #1 oci_field_type() example
<?php
// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
// clob_col CLOB, date_col DATE);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
$column_type = oci_field_type($stid, $i);
$column_size = oci_field_size($stid, $i);
echo "<tr>";
echo "<td>$column_name</td>";
echo "<td>$column_type</td>";
echo "<td>$column_size</td>";
echo "</tr>\n";
}
echo "</table>\n";
// Outputs:
// Name Type Length
// NUMBER_COL NUMBER 22
// VARCHAR2_COL VARCHAR2 1
// CLOB_COL CLOB 4000
// DATE_COL DATE 7
oci_free_statement($stid);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ocicolumntype() instead. This name still can be used, it was left as alias of oci_field_type() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_free_descriptor — Frees a descriptor
$descriptor
) : boolFrees a descriptor allocated by oci_new_descriptor().
Returns TRUE on success or FALSE on failure.
Note:
This function is commonly used as a method OCI-LOB::free.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_free_statement — Frees all resources associated with statement or cursor
$statement
) : boolFrees resources associated with Oracle's cursor or statement, which was received from as a result of oci_parse() or obtained from Oracle.
statementA valid OCI statement identifier.
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.6.0, PHP 7, PECL OCI8 >= 2.0.0)
oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets
$statement
) : resource Used to fetch consectutive sets of query results after the execution of a stored or anonymous Oracle PL/SQL block where that block returns query results with Oracle's DBMS_SQL.RETURN_RESULT PL/SQL function. This allows PL/SQL blocks to easily return query results.
The child statement can be used with any of the OCI8 fetching functions: oci_fetch(), oci_fetch_all(), oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() or oci_fetch_row()
Child statements inherit their parent statement's prefetch value, or it can be explicitly set with oci_set_prefetch().
statementA valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(). The statement identifier may or may not be associated with a SQL statement that returns Implicit Result Sets.
Returns a statement handle for the next child statement available
on statement. Returns FALSE when child
statements do not exist, or all child statements have been returned
by previous calls
to oci_get_implicit_resultset().
Example #1 Fetching Implicit Result Sets in a loop
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (($stid_c = oci_get_implicit_resultset($stid))) {
echo "<h2>New Implicit Result Set:</h2>\n";
echo "<table>\n";
while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):" ")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
}
// Output is:
// New Implicit Result Set:
// Beijing 190518
// Bern 3095
// Bombay 490231
// New Implicit Result Set:
// CN
// CH
// IN
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 Getting child statement handles individually
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$stid_1 = oci_get_implicit_resultset($stid);
$stid_2 = oci_get_implicit_resultset($stid);
$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
// Output is:
// array(2) {
// ["CITY"]=>
// string(7) "Beijing"
// ["POSTAL_CODE"]=>
// string(6) "190518"
// }
// array(1) {
// ["COUNTRY_ID"]=>
// string(2) "CN"
// }
// array(2) {
// ["CITY"]=>
// string(4) "Bern"
// ["POSTAL_CODE"]=>
// string(4) "3095"
// }
// array(1) {
// ["COUNTRY_ID"]=>
// string(2) "CH"
// }
oci_free_statement($stid);
oci_close($conn);
?>
Example #3 Explicitly setting the Prefetch Count
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$stid_c = oci_get_implicit_resultset($stid);
oci_set_prefetch($stid_c, 200); // Set the prefetch before fetching from the child statement
echo "<table>\n";
while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):" ")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>
Example #4 Implicit Result Set example without using oci_get_implicit_resultset()
All results from all queries are returned consecutively.
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):" ")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
// Output is:
// Beijing 190518
// Bern 3095
// Bombay 490231
// CN
// CH
// IN
oci_free_statement($stid);
oci_close($conn);
?>
Note:
For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_internal_debug — Enables or disables internal debug output
$onoff
) : voidEnables or disables internal debug output.
onoff
Set this to FALSE to turn debug output off or TRUE to turn it on.
No value is returned.
Note:
In PHP versions before 5.0.0 you must use ociinternaldebug() instead. This name still can be used, it was left as alias of oci_internal_debug() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_lob_copy — Copies large object
$lob_to
, OCI-Lob $lob_from
[, int $length = 0
] ) : boolCopies a large object or a part of a large object to another large object. Old LOB-recipient data will be overwritten.
If you need to copy a particular part of a LOB to a particular position of a LOB, use OCI-Lob::seek() to move LOB internal pointers.
lob_toThe destination LOB.
lob_fromThe copied LOB.
lengthIndicates the length of data to be copied.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_lob_is_equal — Compares two LOB/FILE locators for equality
$lob1
, OCI-Lob $lob2
) : boolCompares two LOB/FILE locators.
lob1A LOB identifier.
lob2A LOB identifier.
Returns TRUE if these objects are equal, FALSE otherwise.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_new_collection — Allocates new collection object
$connection
, string $tdo
[, string $schema = NULL
] ) : OCI-CollectionAllocates a new collection object.
connectionAn Oracle connection identifier, returned by oci_connect() or oci_pconnect().
tdoShould be a valid named type (uppercase).
schemaShould point to the scheme, where the named type was created. The name of the current user is the default value.
Returns a new OCICollection object or FALSE on
error.
Note:
In PHP versions before 5.0.0 you must use ocinewcollection() instead. This name still can be used, it was left as alias of oci_new_collection() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_new_connect — Connect to the Oracle server using a unique connection
$username
, string $password
[, string $connection_string
[, string $character_set
[, int $session_mode
]]] ) : resourceEstablishes a new connection to an Oracle server and logs on.
Unlike oci_connect() and oci_pconnect(), oci_new_connect() does not cache connections and will always return a brand-new freshly opened connection handle. This is useful if your application needs transactional isolation between two sets of queries.
usernameThe Oracle user name.
password
The password for username.
connection_stringContains
the Oracle instance to connect to. It can be
an » Easy Connect
string, or a Connect Name from
the tnsnames.ora file, or the name of a local
Oracle instance.
If not specified, PHP uses
environment variables such as TWO_TASK (on Linux)
or LOCAL (on Windows)
and ORACLE_SID to determine the
Oracle instance to connect to.
To use the Easy Connect naming method, PHP must be linked with Oracle
10g or greater Client libraries. The Easy Connect string for Oracle
10g is of the form:
[//]host_name[:port][/service_name]. From Oracle
11g, the syntax is:
[//]host_name[:port][/service_name][:server_type][/instance_name].
Service names can be found by running the Oracle
utility lsnrctl status on the database server
machine.
The tnsnames.ora file can be in the Oracle Net
search path, which
includes $ORACLE_HOME/network/admin
and /etc. Alternatively
set TNS_ADMIN so
that $TNS_ADMIN/tnsnames.ora is read. Make sure
the web daemon has read access to the file.
character_setDetermines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.
If not specified, the
Oracle Client libraries determine a character set from
the NLS_LANG environment variable.
Passing this parameter can reduce the time taken to connect.
session_modeThis
parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the
following values: OCI_DEFAULT,
OCI_SYSOPER and OCI_SYSDBA.
If either OCI_SYSOPER or
OCI_SYSDBA were specified, this function will try
to establish privileged connection using external credentials.
Privileged connections are disabled by default. To enable them you
need to set oci8.privileged_connect
to On.
PHP 5.3 (PECL OCI8 1.3.4) introduced the
OCI_CRED_EXT mode value. This tells Oracle to use
External or OS authentication, which must be configured in the
database. The OCI_CRED_EXT flag can only be used
with username of "/" and a empty password.
oci8.privileged_connect
may be On or Off.
OCI_CRED_EXT may be combined with the
OCI_SYSOPER or
OCI_SYSDBA modes.
OCI_CRED_EXT is not supported on Windows for
security reasons.
Returns a connection identifier or FALSE on error.
The following demonstrates how you can separate connections.
Example #1 oci_new_connect() example
<?php
// create table mytab (mycol number);
function query($name, $c)
{
echo "Querying $name\n";
$s = oci_parse($c, "select * from mytab");
oci_execute($s, OCI_NO_AUTO_COMMIT);
$row = oci_fetch_array($s, OCI_ASSOC);
if (!$row) {
echo "No rows\n";
} else {
do {
foreach ($row as $item)
echo $item . " ";
echo "\n";
} while (($row = oci_fetch_array($s, OCI_ASSOC)) != false);
}
}
$c1 = oci_connect("hr", "welcome", "localhost/orcl");
$c2 = oci_new_connect("hr", "welcome", "localhost/orcl");
$s = oci_parse($c1, "insert into mytab values(1234)");
oci_execute($s, OCI_NO_AUTO_COMMIT);
query("basic connection", $c1);
query("new connection", $c2);
oci_commit($c1);
query("new connection after commit", $c2);
// Output is:
// Querying basic connection
// 1234
// Querying new connection
// No rows
// Querying new connection after commit
// 1234
?>
See oci_connect() for further examples of parameter usage.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_new_cursor — Allocates and returns a new cursor (statement handle)
$connection
) : resourceAllocates a new statement handle on the specified connection.
Returns a new statement handle, or FALSE on error.
Example #1 Binding a REF CURSOR in an Oracle stored procedure call
<?php
// Precreate:
// create or replace procedure myproc(myrc out sys_refcursor) as
// begin
// open myrc for select first_name from employees;
// end;
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$curs = oci_new_cursor($conn);
$stid = oci_parse($conn, "begin myproc(:cursbv); end;");
oci_bind_by_name($stid, ":cursbv", $curs, -1, OCI_B_CURSOR);
oci_execute($stid);
oci_execute($curs); // Execute the REF CURSOR like a normal statement id
while (($row = oci_fetch_array($curs, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo $row['FIRST_NAME'] . "<br />\n";
}
oci_free_statement($stid);
oci_free_statement($curs);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ocinewcursor() instead. This name still can be used, it was left as alias of oci_new_cursor() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_new_descriptor — Initializes a new empty LOB or FILE descriptor
$connection
[, int $type = OCI_DTYPE_LOB
] ) : OCI-LobAllocates resources to hold descriptor or LOB locator.
connectionAn Oracle connection identifier, returned by oci_connect() or oci_pconnect().
type
Valid values for type are:
OCI_DTYPE_FILE, OCI_DTYPE_LOB and
OCI_DTYPE_ROWID.
Returns a new LOB or FILE descriptor on success, FALSE on error.
Example #1 oci_new_descriptor() example
<?php
/* This script is designed to be called from a HTML form.
* It expects $user, $password, $table, $where, and $commitsize
* to be passed in from the form. The script then deletes
* the selected rows using the ROWID and commits after each
* set of $commitsize rows. (Use with care, there is no rollback)
*/
$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "select rowid from $table $where");
$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_define_by_name($stmt, "ROWID", $rowid);
oci_execute($stmt);
while (oci_fetch($stmt)) {
$nrows = oci_num_rows($stmt);
$delete = oci_parse($conn, "delete from $table where ROWID = :rid");
oci_bind_by_name($delete, ":rid", $rowid, -1, OCI_B_ROWID);
oci_execute($delete);
echo "$nrows\n";
if (($nrows % $commitsize) == 0) {
oci_commit($conn);
}
}
$nrows = oci_num_rows($stmt);
echo "$nrows deleted...\n";
oci_free_statement($stmt);
oci_close($conn);
?>
<?php
/* This script demonstrates file upload to LOB columns
* The formfield used for this example looks like this
* <form action="upload.php" method="post" enctype="multipart/form-data">
* <input type="file" name="lob_upload" />
* ...
*/
if (!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload" /><br />
<input type="submit" value="Upload" /> - <input type="reset" value="Reset" />
</form>
<?php
} else {
// $lob_upload contains the temporary filename of the uploaded file
// see also the features section on file upload,
// if you would like to use secure uploads
$conn = oci_connect($user, $password);
$lob = oci_new_descriptor($conn, OCI_D_LOB);
$stmt = oci_parse($conn, "insert into $table (id, the_blob)
values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
oci_bind_by_name($stmt, ':the_blob', $lob, -1, OCI_B_BLOB);
oci_execute($stmt, OCI_DEFAULT);
if ($lob->savefile($lob_upload)){
oci_commit($conn);
echo "Blob successfully uploaded\n";
}else{
echo "Couldn't upload Blob\n";
}
$lob->free();
oci_free_statement($stmt);
oci_close($conn);
}
?>
Example #2 oci_new_descriptor() example
<?php
/* Calling PL/SQL stored procedures which contain clobs as input
* parameters.
* Example PL/SQL stored procedure signature is:
*
* PROCEDURE save_data
* Argument Name Type In/Out Default?
* ------------------------------ ----------------------- ------ --------
* KEY NUMBER(38) IN
* DATA CLOB IN
*
*/
$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "begin save_data(:key, :data); end;");
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':key', $key);
oci_bind_by_name($stmt, ':data', $clob, -1, OCI_B_CLOB);
$clob->write($data);
oci_execute($stmt, OCI_DEFAULT);
oci_commit($conn);
$clob->free();
oci_free_statement($stmt);
?>
Note:
In PHP versions before 5.0.0 you must use ocinewdescriptor() instead. This name still can be used, it was left as alias of oci_new_descriptor() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_num_fields — Returns the number of result columns in a statement
$statement
) : int
Gets the number of columns in the given statement.
statementA valid OCI statement identifier.
Returns the number of columns as an integer, or FALSE on errors.
Example #1 oci_num_fields() example
<?php
// Create the table with:
// CREATE TABLE mytab (id NUMBER, quantity NUMBER);
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
echo oci_field_name($stid, $i) . " " . oci_field_type($stid, $i) . "<br>\n";
}
// Outputs:
// ID NUMBER
// QUANTITY NUMBER
oci_free_statement($stid);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ocinumcols() instead. This name still can be used, it was left as alias of oci_num_fields() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_num_rows — Returns number of rows affected during statement execution
$statement
) : intGets the number of rows affected during statement execution.
statementA valid OCI statement identifier.
Returns the number of rows affected as an integer, or FALSE on errors.
Example #1 oci_num_rows() example
<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, "create table emp2 as select * from employees");
oci_execute($stid);
echo oci_num_rows($stid) . " rows inserted.<br />\n";
oci_free_statement($stid);
$stid = oci_parse($conn, "delete from emp2");
oci_execute($stid, OCI_DEFAULT);
echo oci_num_rows($stid) . " rows deleted.<br />\n";
oci_commit($conn);
oci_free_statement($stid);
$stid = oci_parse($conn, "drop table emp2");
oci_execute($stid);
oci_free_statement($stid);
oci_close($conn);
?>
Note:
This function does not return number of rows selected! For SELECT statements this function will return the number of rows, that were fetched to the buffer with oci_fetch*() functions.
Note:
In PHP versions before 5.0.0 you must use ocirowcount() instead. This name still can be used, it was left as alias of oci_num_rows() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_parse — Prepares an Oracle statement for execution
$connection
, string $sql_text
) : resource
Prepares sql_text using
connection and returns the statement identifier,
which can be used with oci_bind_by_name(),
oci_execute() and other functions.
Statement identifiers can be freed
with oci_free_statement() or by setting the
variable to NULL.
connectionAn Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().
sql_textThe SQL or PL/SQL statement.
SQL statements should not end with a semi-colon (";"). PL/SQL statements should end with a semi-colon (";").
Returns a statement handle on success, or FALSE on error.
Example #1 oci_parse() example for SQL statements
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
// Parse the statement. Note there is no final semi-colon in the SQL statement
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
Example #2 oci_parse() example for PL/SQL statements
<?php
/*
Before running the PHP program, create a stored procedure in
SQL*Plus or SQL Developer:
CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
BEGIN
p2 := p1 * 2;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$p1 = 8;
// When parsing PL/SQL programs, there should be a final semi-colon in the string
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);
oci_execute($stid);
print "$p2\n"; // prints 16
oci_free_statement($stid);
oci_close($conn);
?>
Note:
This function does not validate
sql_text. The only way to find out ifsql_textis a valid SQL or PL/SQL statement is to execute it.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_password_change — Changes password of Oracle's user
$connection
, string $username
, string $old_password
, string $new_password
) : bool$dbname
, string $username
, string $old_password
, string $new_password
) : resource
Changes password for user with username.
The oci_password_change() function is most useful for PHP command-line scripts, or when non-persistent connections are used throughout the PHP application.
connectionAn Oracle connection identifier, returned by oci_connect() or oci_pconnect().
usernameThe Oracle user name.
old_passwordThe old password.
new_passwordThe new password to be set.
dbnameThe database name.
Returns TRUE on success or FALSE on failure.
Example #1 oci_password_change() example changing the password of an already connected user
<?php
$dbase = 'localhost/orcl';
$user = 'cj';
$current_pw = 'welcome';
$new_pw = 'geelong';
$c = oci_pconnect($user, $current_pw, $dbase);
oci_password_change($c, $user, $current_pw, $new_pw);
echo "New password is : " . $new_pw . "\n";
?>
Example #2 oci_password_change() example of connecting and changing the password in one step
<?php
$dbase = 'localhost/orcl';
$user = 'cj';
$current_pw = 'welcome';
$new_pw = 'geelong';
$c = oci_pconnect($user, $current_pw, $dbase);
if (!$c) {
$m = oci_error();
if ($m['code'] == 28001) { // "ORA-28001: the password has expired"
// Login and reset password at the same time
$c = oci_password_change($dbase, $user, $current_pw, $new_pw);
if ($c) {
echo "New password is : " . $new_pw . "\n";
}
}
}
if (!$c) { // The original error wasn't 28001, or the password change failed
$m = oci_error();
trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}
// Use the connection $c
...
?>
Note:
Changing the password either with this function or directly in Oracle should be done carefully. This is because PHP applications may continue to successfully reuse persistent connections by authenticating with the old password. The best practice is to restart all web servers whenever the user password is changed.
Note:
If upgrading the Oracle client libraries or the database from a release prior to 11.2.0.3 to version 11.2.0.3 or higher, oci_password_change() may give the error "ORA-1017: invalid username/password" unless both client and server versions are upgraded at the same time.
Note:
The second oci_password_change() syntax is available since OCI8 version 1.1.
Note:
In PHP versions before 5.0.0 you must use ocipasswordchange() instead. This name still can be used, it was left as alias of oci_password_change() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_pconnect — Connect to an Oracle database using a persistent connection
$username
, string $password
[, string $connection_string
[, string $character_set
[, int $session_mode
]]] ) : resourceCreates a persistent connection to an Oracle server and logs on.
Persistent connections are cached and re-used between requests, resulting in reduced overhead on each page load; a typical PHP application will have a single persistent connection open against an Oracle server per Apache child process (or PHP FastCGI/CGI process). See the Persistent Database Connections section for more information.
usernameThe Oracle user name.
password
The password for username.
connection_stringContains
the Oracle instance to connect to. It can be
an » Easy Connect
string, or a Connect Name from
the tnsnames.ora file, or the name of a local
Oracle instance.
If not specified, PHP uses
environment variables such as TWO_TASK (on Linux)
or LOCAL (on Windows)
and ORACLE_SID to determine the
Oracle instance to connect to.
To use the Easy Connect naming method, PHP must be linked with Oracle
10g or greater Client libraries. The Easy Connect string for Oracle
10g is of the form:
[//]host_name[:port][/service_name]. From Oracle
11g, the syntax is:
[//]host_name[:port][/service_name][:server_type][/instance_name].
Service names can be found by running the Oracle
utility lsnrctl status on the database server
machine.
The tnsnames.ora file can be in the Oracle Net
search path, which
includes $ORACLE_HOME/network/admin
and /etc. Alternatively
set TNS_ADMIN so
that $TNS_ADMIN/tnsnames.ora is read. Make sure
the web daemon has read access to the file.
character_setDetermines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.
If not specified, the
Oracle Client libraries determine a character set from
the NLS_LANG environment variable.
Passing this parameter can reduce the time taken to connect.
session_modeThis
parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the
following values: OCI_DEFAULT,
OCI_SYSOPER and OCI_SYSDBA.
If either OCI_SYSOPER or
OCI_SYSDBA were specified, this function will try
to establish privileged connection using external credentials.
Privileged connections are disabled by default. To enable them you
need to set oci8.privileged_connect
to On.
PHP 5.3 (PECL OCI8 1.3.4) introduced the
OCI_CRED_EXT mode value. This tells Oracle to use
External or OS authentication, which must be configured in the
database. The OCI_CRED_EXT flag can only be used
with username of "/" and a empty password.
oci8.privileged_connect
may be On or Off.
OCI_CRED_EXT may be combined with the
OCI_SYSOPER or
OCI_SYSDBA modes.
OCI_CRED_EXT is not supported on Windows for
security reasons.
Returns a connection identifier or FALSE on error.
Example #1 Basic oci_pconnect() Example using Easy Connect syntax
<?php
// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_pconnect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
See oci_connect() for further examples of parameter usage.
Note: Starting with PHP 5.1.2 and PECL OCI8 1.1, the lifetime and maximum number of persistent Oracle connections per PHP process can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.
(PHP 7.0 >= 7.0.21, PHP 7 >= 7.1.7, PECL OCI8 >= 2.1.7)
oci_register_taf_callback — Register a user-defined callback function for Oracle Database TAF
Registers a user-defined callback function to connection.
If connection fails due to instance or network failure,
the registered callback function will be invoked for several times during
failover. See OCI8 Transparent Application Failover
(TAF) Support for information.
When oci_register_taf_callback() is called multiple times, each registration overwrites the previous one.
Use oci_unregister_taf_callback() to explicitly unregister a user-defined callback.
TAF callback registration will NOT be saved across persistent connections, therefore the callback needs to be re-registered for a new persistent connection.
connectionAn Oracle connection identifier.
callbackFnA user-defined callback to register for Oracle TAF. It can be a string of the function name or a Closure (anonymous function).
The interface of a TAF user-defined callback function is as follows:
$connection
, int $event
, int $type
) : intSee the parameter description and an example on OCI8 Transparent Application Failover (TAF) Support page.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_result — Returns field's value from the fetched row
Returns the data from field in the current row,
fetched by oci_fetch().
For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver
statement
fieldCan be either use the column number (1-based) or the column name. The case of the column name must be the case that Oracle meta data describes the column as, which is uppercase for columns created case insensitively.
Returns everything as strings except for abstract types (ROWIDs, LOBs and
FILEs). Returns FALSE on error.
Example #1 oci_fetch() with oci_result()
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (oci_fetch($stid)) {
echo oci_result($stid, 'LOCATION_ID') . " is ";
echo oci_result($stid, 'CITY') . "<br>\n";
}
// Displays:
// 1000 is Roma
// 1100 is Venice
oci_free_statement($stid);
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ociresult() instead. This name still can be used, it was left as alias of oci_result() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_rollback — Rolls back the outstanding database transaction
$connection
) : bool
Reverts all uncommitted changes for the Oracle
connection and ends the transaction. It
releases all locks held. All Oracle SAVEPOINTS
are erased.
A transaction begins when the first SQL statement that changes data
is executed with oci_execute() using
the OCI_NO_AUTO_COMMIT flag. Further data
changes made by other statements become part of the same
transaction. Data changes made in a transaction are temporary
until the transaction is committed or rolled back. Other users of
the database will not see the changes until they are committed.
When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.
connectionAn Oracle connection identifier, returned by oci_connect(), oci_pconnect() or oci_new_connect().
Returns TRUE on success or FALSE on failure.
Example #1 oci_rollback() example
<?php
// Insert into several tables, rolling back the changes if an error occurs
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1. The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
oci_rollback($conn); // rollback changes to both tables
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
// Commit the changes to both tables
$r = oci_commit($conn);
if (!r) {
$e = oci_error($conn);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>
Example #2 Rolling back to a SAVEPOINT example
<?php
$stid = oci_parse($conn, 'UPDATE mytab SET id = 1111');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
// Create the savepoint
$stid = oci_parse($conn, 'SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
$stid = oci_parse($conn, 'UPDATE mytab SET id = 2222');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
// Use an explicit SQL statement to rollback to the savepoint
$stid = oci_parse($conn, 'ROLLBACK TO SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
oci_commit($conn); // mytab now has id of 1111
?>
Note:
Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.
Any call to oci_execute() that uses
OCI_COMMIT_ON_SUCCESSmode explicitly or by default will commit any previous uncommitted transaction.Any Oracle DDL statement such as
CREATEorDROPwill automatically commit any uncommitted transaction.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_server_version — Returns the Oracle Database version
$connection
) : stringReturns a string with the Oracle Database version and available options
connection
Returns the version information as a string or FALSE on error.
Example #1 oci_server_version() example
<?php
$conn = oci_connect("hr", "hrpwd", "localhost/XE");
echo "Server Version: " . oci_server_version($conn);
// Displays:
// Server Version: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
// With the Partitioning, OLAP, Data Mining and Real Application Testing option
oci_close($conn);
?>
Note:
In PHP versions before 5.0.0 you must use ociserverversion() instead. This old name still can be used. However it is deprecated and not recommended.
(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)
oci_set_action — Sets the action name
$connection
, string $action_name
) : boolSets the action name for Oracle tracing.
The action name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.
The action name can subsequently be queried from database administration
views such as V$SESSION. It can be used for
tracing and monitoring such as with V$SQLAREA
and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.
The value may be retained across persistent connections.
connectionAn Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().
action_nameUser chosen string up to 32 bytes long.
Returns TRUE on success or FALSE on failure.
Example #1 Setting the action
<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');
// Record the action
oci_set_action($c, 'Friend Lookup');
// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);
sleep(30);
?>
// While the script is running, the administrator can see the actions // being performed: sqlplus system/welcome SQL> select action from v$session;
Note: Oracle version requirement
This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.
With older versions of
OCI8 or the Oracle Database, the client information can be set using the Oracle
DBMS_APPLICATION_INFO package. This is less efficient than
using oci_set_client_info().
Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.
(PHP 7.2 >= 7.2.14, PHP 7 >= 7.3.1, PECL OCI8 >= 2.2.0)
oci_set_call_timeout — Sets a millisecond timeout for database calls
$connection
, int $time_out
) : boolSets a timeout limiting the maxium time a database round-trip using this connection may take.
Each OCI8 operation may make zero or more calls to Oracle's client
library. These internal calls may then may make zero or more
round-trips to Oracle Database. If any one of those round-trips
takes more than time_out milliseconds, then the
operation is cancelled and an error is returned to the application.
The time_out value applies to each round-trip
individually, not to the sum of all round-trips. Time spent
processing in PHP OCI8 before or after the completion of each
round-trip is not counted.
When a call is interrupted, Oracle will attempt to clean up the
connection for reuse. This operation is allowed to run for
another time_out period. Depending on the
outcome of the cleanup, the connection may or may not be reusable.
When persistent connections are used, the timeout value will be retained across PHP requests.
The oci_set_call_timeout() function is available when OCI8 uses Oracle 18 (or later) Client libraries.
connectionAn Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().
time_outThe maximum time in milliseconds that any single round-trip between PHP and Oracle Database may take.
Returns TRUE on success or FALSE on failure.
Example #1 Setting the timeout
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
oci_set_call_timeout($conn, 5000);
?>
(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)
oci_set_client_identifier — Sets the client identifier
$connection
, string $client_identifier
) : boolSets the client identifier used by various database components to identify lightweight application users who authenticate as the same database user.
The client identifier is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.
The identifier can subsequently be queried, for example
with SELECT SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER')
FROM DUAL. Database administration views such
as V$SESSION will also contain the value. It
can be used with DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE
for tracing and can also be used for auditing.
The value may be retained across page requests that use the same persistent connection.
connectionAn Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().
client_identifierUser chosen string up to 64 bytes long.
Returns TRUE on success or FALSE on failure.
Example #1 Setting the client identifier to the application user
<?php
// Find the application user's login name
session_start();
$un = my_validate_session($_SESSION['username']);
$c = oci_connect('myschema', 'welcome', 'localhost/XE');
// Tell Oracle who that user is
oci_set_client_identifier($c, $un);
// The next round-trip to the database will piggyback the identifier
$s = oci_parse($c, 'select mydata from mytable');
oci_execute($s);
// ...
?>
Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.
(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)
oci_set_client_info — Sets the client information
$connection
, string $client_info
) : boolSets the client information for Oracle tracing.
The client information is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.
The client information can subsequently be queried from database
administration views such as V$SESSION.
The value may be retained across persistent connections.
connectionAn Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().
client_infoUser chosen string up to 64 bytes long.
Returns TRUE on success or FALSE on failure.
Example #1 Setting the client information
<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');
// Record the client information
oci_set_client_info($c, 'My Application Version 2');
// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);
sleep(30);
?>
// While the script is running, the administrator can see the client // information: sqlplus system/welcome SQL> select client_info from v$session;
Note: Oracle version requirement
This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.
With older versions of
OCI8 or the Oracle Database, the client information can be set using the Oracle
DBMS_APPLICATION_INFO package. This is less efficient than
using oci_set_client_info().
Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.
(PHP 7 >= 7.2.14, PHP 7 >= 7.3.1, PECL OCI8 >= 2.2.0)
oci_set_db_operation — Sets the database operation
$connection
, string $dbop
) : boolSets the DBOP for Oracle tracing.
The database operation name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when a SQL statement is executed.
The database operation can subsequently be queried from database administration
views such as V$SQL_MONITOR.
The oci_set_db_operation() function is available when OCI8 uses Oracle 12 (or later) Client libraries and Oracle Database 12 (or later).
connectionAn Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().
dbopUser chosen string.
Returns TRUE on success or FALSE on failure.
Example #1 Setting the DBOP
<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');
// Record the operation
oci_set_db_operation($c, 'main query');
// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);
sleep(30);
?>
// While the script is running, the administrator can see the database operations // being performed: sqlplus system/welcome SQL> select dbop_name from v$sql_monitor;
Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.
(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)
oci_set_edition — Sets the database edition
$edition
) : boolSets the database "edition" of objects to be used by a subsequent connections.
Oracle Editions allow concurrent versions of applications to run using the same schema and object names. This is useful for upgrading live systems.
Call oci_set_edition() before calling oci_connect(), oci_pconnect() or oci_new_connect().
If an edition is set that is not valid in the database, connection will fail even if oci_set_edition() returns success.
When using persistent connections, if a connection with the requested edition setting already exists, it is reused. Otherwise, a different persistent connection is created
edition
Oracle Database edition name previously created with the SQL
"CREATE EDITION" command.
Note: Oracle version requirement
This function is available from Oracle 11gR2 onwards.
To avoid inconsistencies and unexpected errors, do not use ALTER SESSION SET EDITION to change the edition on persistent connections.
To avoid inconsistencies and unexpected errors when using editions and DRCP with Oracle 11.2.0.1, keep a one-to-one correspondence between the oci8.connection_class and the edition name used by applications. Each pooled server of a given connection class should only be used with one edition. This restriction has been removed with Oracle 11.2.0.2.
Returns TRUE on success or FALSE on failure.
Example #1 Two scripts can use different versions of myfunc() at the same time
<?php
// File 1
echo "Version 1 of application\n";
oci_set_edition('ORA$BASE');
$c = oci_connect('hr', 'welcome', 'localhost/XE');
$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";
?>
<?php
// File 2
echo "Version 2 of application\n";
oci_set_edition('E1');
$c = oci_connect('hr', 'welcome', 'localhost/XE');
$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";
?>
(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)
oci_set_module_name — Sets the module name
$connection
, string $module_name
) : boolSets the module name for Oracle tracing.
The module name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.
The name can subsequently be queried from database administration
views such as V$SESSION. It can be used for
tracing and monitoring such as with V$SQLAREA
and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.
The value may be retained across persistent connections.
connectionAn Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().
module_nameUser chosen string up to 48 bytes long.
Returns TRUE on success or FALSE on failure.
Note: Oracle version requirement
This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.
With older versions of
OCI8 or the Oracle Database, the client information can be set using the Oracle
DBMS_APPLICATION_INFO package. This is less efficient than
using oci_set_client_info().
Some but not all OCI8 functions cause round-trips. Round-trips to the database may not occur with queries when result caching is enabled.
Example #1 Setting the module name
<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');
// Record the module
oci_set_module_name($c, 'Home Page');
// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);
sleep(30);
?>
// While the script is running, the administrator can see the // modules in use: sqlplus system/welcome SQL> select module from v$session;
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_set_prefetch — Sets number of rows to be prefetched by queries
$statement
, int $rows
) : boolSets the number of rows to be buffered by the Oracle Client libraries after a successful query call to oci_execute() and for each subsequent internal fetch request to the database. For queries returning a large number of rows, performance can be significantly improved by increasing the prefetch count above the default oci8.default_prefetch value.
Prefetching is Oracle's efficient way of returning more than one data row from the database in each network request. This can result in better network and CPU utilization. The buffering of rows is internal to OCI8 and the behavior of OCI8 fetching functions is unchanged regardless of the prefetch count. For example, oci_fetch_row() will always return one row. The prefetch buffer is per-statement and is not used by re-executed statements or by other connections.
Call oci_set_prefetch() before calling oci_execute().
A tuning goal is to set the prefetch value to a reasonable size for the network and database to handle. For queries returning a very large number of rows, overall system efficiency might be better if rows are retrieved from the database in several chunks (i.e set the prefetch value smaller than the number of rows). This allows the database to handle other users' statements while the PHP script is processing the current set of rows.
Query prefetching was introduced in Oracle 8i. REF CURSOR prefetching was introduced in Oracle 11gR2 and occurs when PHP is linked with Oracle 11gR2 (or later) Client libraries. Nested cursor prefetching was introduced in Oracle 11gR2 and requires both the Oracle Client libraries and the database to be version 11gR2 or greater.
Prefetching is not supported when queries contain LONG or LOB columns. The prefetch value is ignored and single-row fetches will be used in all the situations when prefetching is not supported.
When using Oracle Database 12c, the prefetch
value set by PHP can be overridden by Oracle's
client oraaccess.xml configuration file. Refer
to Oracle documentation for more detail.
statementA valid OCI8 statement
identifier created by oci_parse() and executed
by oci_execute(), or a REF
CURSOR statement identifier.
rowsThe number of rows to be prefetched, >= 0
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.2 (PECL OCI8 1.4) |
Before this release, rows must be >= 1.
|
| 5.3.0 (PECL OCI8 1.3.4) |
Before this release, prefetching was limited to the lesser
of rows rows and 1024
* rows bytes. The byte size
restriction has now been removed.
|
Example #1 Changing the default prefetch value for a query
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM myverybigtable');
oci_set_prefetch($stid, 300); // Set before calling oci_execute()
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : " ")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid);
oci_close($conn);
?>
Example #2 Changing the default prefetch for a REF CURSOR fetch
<?php
/*
Create the PL/SQL stored procedure as:
CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
BEGIN
OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
END;
*/
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);
// Change the prefetch before executing the cursor.
// REF CURSOR prefetching works when PHP is linked with Oracle 11gR2 or later Client libraries
oci_set_prefetch($refcur, 200);
oci_execute($refcur);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : " ")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);
?>
If PHP OCI8 fetches from a REF CURSOR and then passes the REF
CURSOR back to a second PL/SQL procedure for further processing,
then set the REF CURSOR prefetch count to 0 to
avoid rows being "lost" from the result set. The prefetch value is
the number of extra rows fetched in each OCI8 internal request to
the database, so setting it to 0 means only
fetch one row at a time.
Example #3 Setting the prefetch value when passing a REF CURSOR back to Oracle
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/orcl');
// get the REF CURSOR
$stid = oci_parse($conn, 'BEGIN myproc(:rc_out); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc_out', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);
// Display two rows, but don't prefetch any extra rows otherwise
// those extra rows would not be passed back to myproc_use_rc().
// A prefetch value of 0 is allowed in PHP 5.3.2 and PECL OCI8 1.4
oci_set_prefetch($refcur, 0);
oci_execute($refcur);
$row = oci_fetch_array($refcur);
var_dump($row);
$row = oci_fetch_array($refcur);
var_dump($row);
// pass the REF CURSOR to myproc_use_rc() to do more data processing
// with the result set
$stid = oci_parse($conn, 'begin myproc_use_rc(:rc_in); end;');
oci_bind_by_name($stid, ':rc_in', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);
?>
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
oci_statement_type — Returns the type of a statement
$statement
) : string
Returns a keyword identifying the type of the
OCI8 statement.
Returns the type of statement as one of the
following strings.
| Return String | Notes |
|---|---|
ALTER |
|
BEGIN |
|
CALL |
Introduced in PHP 5.2.1 (PECL OCI8 1.2.3) |
CREATE |
|
DECLARE |
|
DELETE |
|
DROP |
|
INSERT |
|
SELECT |
|
UPDATE |
|
UNKNOWN |
Returns FALSE on error.
Example #1 oci_statement_type() example
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'DELETE FROM departments WHERE department_id = 130;');
if (oci_statement_type($stid) == "DELETE") {
trigger_error('You are not allowed to delete from this table', E_USER_ERROR);
}
else {
oci_execute($stid); // delete the row
}
oci_free_statement($stid);
oci_close($conn);
?>
(PHP 7.0 >= 7.0.23, PHP 7 >= 7.1.9, PECL OCI8 >= 2.1.7)
oci_unregister_taf_callback — Unregister a user-defined callback function for Oracle Database TAF
$connection
) : bool
Unregister the user-defined callback function registered to connection
by oci_register_taf_callback(). See
OCI8 Transparent Application Failover (TAF) Support
for information.
connectionAn Oracle connection identifier.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI8 Collection functionality.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Collection::append — Appends element to the collection
Appends element to the end of the collection.
valueThe value to be added to the collection. Can be a string or a number.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Collection::assign — Assigns a value to the collection from another existing collection
$from
) : boolAssigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.
fromAn instance of OCI-Collection.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Collection::assignElem — Assigns a value to the element of the collection
Assigns a value to the element with index index.
indexThe element index. First index is 0.
valueCan be a string or a number.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Collection::free — Frees the resources associated with the collection object
Frees the resources associated with the collection object.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Collection::getElem — Returns value of the element
Returns element's value with the index index (0-based).
indexThe element index. First index is 0.
Returns FALSE if such element doesn't exist; NULL if element is NULL;
string if element is column of a string datatype or number if element is
numeric field.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Collection::max — Returns the maximum number of elements in the collection
Returns the maximum number of elements in the collection.
Returns the maximum number as an integer, or FALSE on errors.
If the returned value is 0, then the number of elements is not limited.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Collection::size — Returns size of the collection
Returns the size of the collection.
Returns the number of elements in the collection or FALSE on error.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Collection::trim — Trims elements from the end of the collection
$num
) : bool
Trims num of elements from the end of the
collection.
numThe number of elements to be trimmed.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI8 LOB functionality for large binary (BLOB) and character (CLOB) objects.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::append — Appends data from the large object to another large object
$lob_from
) : boolAppends data from the large object to the end of another large object.
Writing to the large object with this method will fail if buffering was previously enabled. You must disable buffering before appending. You may need to flush buffers with OCI-Lob::flush before disabling buffering.
lob_fromThe copied LOB.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::close — Closes LOB descriptor
Closes descriptor of LOB or FILE. This function should be used only with OCI-Lob::writeTemporary.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::eof — Tests for end-of-file on a large object's descriptor
Tells whether the internal pointer of large object is at the end of LOB.
Returns TRUE if internal pointer of large object is at the end of LOB.
Otherwise returns FALSE.
Note:
This function will return an Oracle error if OCI-Lob::setBuffering is enabled on the LOB.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::erase — Erases a specified portion of the internal LOB data
$offset
[, int $length
]] ) : int
Erases a specified portion of the internal LOB data starting at a
specified offset. If called without parameters, it
erases all LOB data.
For BLOBs, erasing means that the existing LOB value is overwritten with zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.
offset
length
Returns the actual number of characters/bytes erased or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::export — Exports LOB's contents to a file
$filename
[, int $start
[, int $length
]] ) : boolExports LOB contents to a file.
filenamePath to the file.
startIndicates from where to start exporting.
lengthIndicates the length of data to be exported.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::flush — Flushes/writes buffer of the LOB to the server
$flag
] ) : boolOCI-Lob::flush() actually writes data to the server.
flag
By default, resources are not freed, but using flag
OCI_LOB_BUFFER_FREE you can do it explicitly.
Be sure you know what you're doing - next read/write operation to the
same part of LOB will involve a round-trip to the server and initialize
new buffer resources. It is recommended to use
OCI_LOB_BUFFER_FREE flag only when you are not
going to work with the LOB anymore.
Returns TRUE on success or FALSE on failure.
Returns FALSE if buffering was not enabled or an error occurred.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::free — Frees resources associated with the LOB descriptor
Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::getBuffering — Returns current state of buffering for the large object
Tells whether the buffering for the large object is on or off.
Returns FALSE if buffering for the large object is off and TRUE if
buffering is used.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::import — Imports file data to the LOB
$filename
) : bool
Writes data from the filename in to the current
position of large object.
filenamePath to the file.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::load — Returns large object's contents
Returns large object's contents. As script execution is terminated when the memory_limit is reached, ensure that the LOB does not exceed this limit. In most cases it's recommended to use OCI-Lob::read instead.
Returns the contents of the object, or FALSE on errors.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::read — Reads part of the large object
$length
) : string
Reads length bytes from the current position of
LOB's internal pointer.
Reading stops when length bytes have been read or
end of the large object is reached. Internal pointer of the large object
will be shifted on the amount of bytes read.
lengthThe length of data to read, in bytes. Large values will be rounded down to 1 MB.
Returns the contents as a string, or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::rewind — Moves the internal pointer to the beginning of the large object
Sets the internal pointer to the beginning of the large object.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::save — Saves data to the large object
$data
[, int $offset
] ) : bool
Saves data to the large object.
dataThe data to be saved.
offsetCan be used to indicate offset from the beginning of the large object.
Returns TRUE on success or FALSE on failure.
This function is an alias of: OCI-Lob::import().
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::seek — Sets the internal pointer of the large object
$offset
[, int $whence = OCI_SEEK_SET
] ) : boolSets the internal pointer of the large object.
offset
Indicates the amount of bytes, on which internal pointer should be
moved from the position, pointed by whence.
whenceMay be one of:
OCI_SEEK_SET - sets the position equal to
offset
OCI_SEEK_CUR - adds offset
bytes to the current position
OCI_SEEK_END - adds offset
bytes to the end of large object (use negative value to move to a position
before the end of large object)
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::setBuffering — Changes current state of buffering for the large object
$on_off
) : bool
Sets the buffering for the large object, depending on the value of the
on_off parameter.
Use of this function may provide performance improvements by buffering small reads and writes of LOBs by reducing the number of network round-trips and LOB versions. OCI-Lob::flush() should be used to flush buffers, when you have finished working with the large object.
on_off
TRUE for on and FALSE for off.
Returns TRUE on success or FALSE on failure. Repeated calls to this method with the same flag will
return TRUE.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::size — Returns size of large object
Gets the size of the large object.
Returns length of large object value or FALSE on failure.
Empty objects have zero length.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::tell — Returns the current position of internal pointer of large object
Gets the current position of a LOB's internal pointer.
Returns current position of a LOB's internal pointer or FALSE if an
error occurred.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::truncate — Truncates large object
$length = 0
] ) : boolTruncates the LOB.
length
If provided, this method will truncate the LOB to
length bytes. Otherwise, it will completely
purge the LOB.
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::write — Writes data to the large object
$data
[, int $length
] ) : int
Writes data from the parameter data into the
current position of LOB's internal pointer.
dataThe data to write in the LOB.
length
If this parameter is given, writing will stop after
length bytes have been written or the end of
data is reached, whichever comes first.
Returns the number of bytes written or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::writeTemporary — Writes a temporary large object
$data
[, int $lob_type = OCI_TEMP_CLOB
] ) : bool
Creates a temporary large object and writes data
to it.
You should use OCI-Lob::close when you are done with this object.
dataThe data to write.
lob_typeCan be one of the following:
OCI_TEMP_BLOB is used to create temporary BLOBs
OCI_TEMP_CLOB is used to create
temporary CLOBs
Returns TRUE on success or FALSE on failure.
(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)
OCI-Lob::writeToFile — Alias of OCI-Lob::export()
This function is an alias of: OCI-Lob::export().
Alias of oci_bind_by_name()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_cancel()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of OCI-Lob::close()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocicollappend — Alias of OCI-Collection::append()
Alias of OCI-Collection::append()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 1.0)
ocicollassign — Alias of OCI-Collection::assign()
Alias of OCI-Collection::assign()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocicollassignelem — Alias of OCI-Collection::assignElem()
Alias of OCI-Collection::assignElem()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocicollgetelem — Alias of OCI-Collection::getElem()
Alias of OCI-Collection::getElem()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocicollmax — Alias of OCI-Collection::max()
Alias of OCI-Collection::max()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocicollsize — Alias of OCI-Collection::size()
Alias of OCI-Collection::size()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocicolltrim — Alias of OCI-Collection::trim()
Alias of OCI-Collection::trim()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocicolumnisnull — Alias of oci_field_is_null()
Alias of oci_field_is_null()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_field_name()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocicolumnprecision — Alias of oci_field_precision()
Alias of oci_field_precision()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_field_scale()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_field_size()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_field_type()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocicolumntyperaw — Alias of oci_field_type_raw()
Alias of oci_field_type_raw()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_commit()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocidefinebyname — Alias of oci_define_by_name()
Alias of oci_define_by_name()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_error()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_execute()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_fetch()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocifetchinto — Obsolete variant of oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_row()
Obsolete variant of oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_row()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocifetchstatement — Alias of oci_fetch_all()
Alias of oci_fetch_all()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.7, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocifreecollection — Alias of OCI-Collection::free()
Alias of OCI-Collection::free()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocifreecursor — Alias of oci_free_statement()
Alias of oci_free_statement()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of OCI-Lob::free()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocifreestatement — Alias of oci_free_statement()
Alias of oci_free_statement()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ociinternaldebug — Alias of oci_internal_debug()
Alias of oci_internal_debug()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of OCI-Lob::load()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_close()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_connect()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocinewcollection — Alias of oci_new_collection()
Alias of oci_new_collection()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_new_cursor()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocinewdescriptor — Alias of oci_new_descriptor()
Alias of oci_new_descriptor()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_new_connect()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_num_fields()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_parse()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_pconnect()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_result()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_rollback()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of oci_num_rows()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of OCI-Lob::save()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
Alias of OCI-Lob::import()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ociserverversion — Alias of oci_server_version()
Alias of oci_server_version()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocisetprefetch — Alias of oci_set_prefetch()
Alias of oci_set_prefetch()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ocistatementtype — Alias of oci_statement_type()
Alias of oci_statement_type()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)
ociwritelobtofile — Alias of OCI-Lob::export()
Alias of OCI-Lob::export()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 1.0)
ociwritetemporarylob — Alias of OCI-Lob::writeTemporary()
Alias of OCI-Lob::writeTemporary()
This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.
This module allows to read and write Paradox databases, primary index files and blob files. Write support has been proven to be quite reliable, though due to lack of documentation the produced files may not in any case be readable by other applications. Encrypted databases can be read without specifying a password if pxlib >= 0.5.0 is used.
Note:
This module is also in development and may change, though major changes to the API are not expected.
This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.
You need at least PHP 5.0.0 and pxlib >= 0.4.4 for the basic set of functions. Some newer functions are only available with pxlib >= 0.6.0. Reading and writing of encrypted databases requires at least pxlib >= 0.5.0. The paradox library (pxlib) is available at » http://pxlib.sourceforge.net.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/paradox
Make sure you have pxlib installed before. If you install pxlib from an rpm or debian package, do not forget to install the development package as well.
This extension has no configuration directives defined in php.ini.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
The following two tables lists all constants defined by the paradox extension.
| Name | Meaning |
|---|---|
| PX_FIELD_ALPHA | Character data with fixed length |
| PX_FIELD_DATE | Date, number of days since 1.1.0000 |
| PX_FIELD_SHORT | Short integer (2 Bytes) |
| PX_FIELD_LONG | Long integer (4 Bytes) |
| PX_FIELD_CURRENCY | same as PX_FIELD_NUMBER |
| PX_FIELD_NUMBER | Double |
| PX_FIELD_LOGICAL | Boolean |
| PX_FIELD_MEMOBLOB | Binary large object |
| PX_FIELD_BLOB | Binary large object (not supported) |
| PX_FIELD_FMTMEMOBLOB | Binary large object |
| PX_FIELD_OLE | OLE object (basically a blob, not supported) |
| PX_FIELD_GRAPHIC | Graphic (basically a blob, not supported) |
| PX_FIELD_TIME | time, number of milli seconds since midnight |
| PX_FIELD_TIMESTAMP | timestamp, number of milli seconds since 1.1.0000 |
| PX_FIELD_AUTOINC | Auto incrementing interger (like PX_FIELD_LONG) |
| PX_FIELD_BCD | Decimal number stored in bcd format (not supported) |
| PX_FIELD_BYTES | Array of Bytes with not more than 255 bytes (not supported) |
| PX_KEYTOLOWER | Turn all field names into lower case |
| PX_KEYTOUPPER | Turn all field names into upper case |
| Name | Meaning |
|---|---|
| PX_FILE_INDEX_DB | Indexed database |
| PX_FILE_PRIM_INDEX | Primary index |
| PX_FILE_NON_INDEX_DB | None indexed database |
| PX_FILE_NON_INC_SEC_INDEX | None incremental secondary index |
| PX_FILE_SEC_INDEX | Secondary index |
| PX_FILE_INC_SEC_INDEX | Incremental secondary index |
| PX_FILE_NON_INC_SEC_INDEX_G | Non incremental secondary index |
| PX_FILE_SEC_INDEX_G | Secondary index |
| PX_FILE_INC_SEC_INDEX_G | Non incremental secondary index |
The paradox extension provides also an object oriented API. It consists of only one class called paradox_db. Its methods only differ from the functions in its name and of course the missing first parameter. The following table will list all methods and its equivalent functions.
| Name of method | Equivalent function |
|---|---|
| Constructor | px_new() |
| Destructor | px_delete() |
| open_fp() | px_open_fp() |
| create_fp() | px_create_fp() |
| close() | px_close() |
| numrecords() | px_numrecords() |
| numfields() | px_numfields() |
| get_record() | px_get_record() |
| put_record() | px_put_record() |
| retrieve_record() | px_retrieve_record() |
| delete_record() | px_delete_record() |
| insert_record() | px_insert_record() |
| update_record() | px_update_record() |
| get_field() | px_get_field() |
| get_schema() | px_get_schema() |
| get_info() | px_get_info() |
| set_parameter() | px_set_parameter() |
| get_parameter() | px_get_parameter() |
| set_value() | px_set_value() |
| get_value() | px_get_value() |
| get_info() | px_get_info() |
| set_targetencoding() | px_set_targetencoding() |
| set_tablename() | px_set_tablename() |
| set_blob_file() | px_set_blob_file() |
| date2string() | px_date2string() |
| timestamp2string() | px_timestamp2string() |
(PECL paradox >= 1.0.0)
px_close — Closes a paradox database
$pxdoc
) : boolCloses the paradox database. This function will not close the file. You will have to call fclose() afterwards.
Returns TRUE on success or FALSE on failure.
(PECL paradox >= 1.0.0)
px_create_fp — Create a new paradox database
$pxdoc
, resource $file
, array $fielddesc
) : boolCreate a new paradox database file. The actual file has to be opened before with fopen(). Make sure the file is writable.
Note:
Calling this functions issues a warning about an empty tablename which can be safely ignored. Just set the tablename afterwards with px_set_parameter().
Note:
This function is highly experimental, due to insufficient documentation of the paradox file format. Database files created with this function can be opened by px_open_fp() and has been successfully opened by the Paradox software, but your milage may vary.
pxdocResource identifier of the paradox database as returned by px_new().
fileFile handle as returned by fopen().
fielddescfielddesc is an array containing one element for each field specification. A field specification is an array itself with either two or three elements.The first element is always a string value used as the name of the field. It may not be larger than ten characters. The second element contains the field type which is one of the constants listed in the table Constants for field types. In the case of a character field or bcd field, you will have to provide a third element specifying the length respectively the precesion of the field. If your field specification contains blob fields, you will have to make sure to either make the field large enough for all field values to fit or specify a blob file with px_set_blob_file() for storing the blobs. If this is not done the field data is truncated.
Returns TRUE on success or FALSE on failure.
Example #1 Creating a Paradox database with two fields
<?php
if(!$pxdoc = px_new()) {
/* Error handling */
}
$fp = fopen("test.db", "w+");
$fields = array(array("col1", "S"), array("col2", "I"));
if(!px_create_fp($pxdoc, $fp, $fields)) {
/* Error handling */
}
px_set_parameter($pxdoc, "tablename", "testtable");
for($i=-50; $i<50; $i++) {
$rec = array($i, -$i);
px_put_record($pxdoc, $rec);
}
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>
(PECL paradox >= 1.4.0)
px_date2string — Converts a date into a string
$pxdoc
, int $value
, string $format
) : stringTurns a date as it stored in the paradox file into human readable format. Paradox dates are the number of days since 1.1.0000. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the example below.
pxdocResource identifier of the paradox database as returned by px_new().
valueValue as stored in paradox database field of type PX_FIELD_DATE.
formatString format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, L).
Returns TRUE on success or FALSE on failure.
Example #1 Turn a paradox date into a human readable form
<?php
$px = px_new();
/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;
/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";
/* px_date2string() outputs the same */
echo px_date2string($px, $days, "n/d/Y")."\n";
px_delete($px);
?>
The above example will output:
7/15/1917 7/15/1917
(PECL paradox >= 1.4.0)
px_delete_record — Deletes record from paradox database
$pxdoc
, int $num
) : boolThis function deletes a record from the database. It does not free the space in the database file but just marks it as deleted. Inserting a new record afterwards will reuse the space.
Note:
This function is only available if pxlib >= 0.6.0 is used.
pxdocResource identifier of the paradox database as returned by px_new().
numThe record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.
Returns TRUE on success or FALSE on failure.
(PECL paradox >= 1.0.0)
px_delete — Deletes resource of paradox database
$pxdoc
) : boolDeletes the resource of the paradox file and frees all memory.
Returns TRUE on success or FALSE on failure.
(PECL paradox >= 1.0.0)
px_get_field — Returns the specification of a single field
$pxdoc
, int $fieldno
) : array
pxdocResource identifier of the paradox database as returned by px_new().
fieldnoNumber of the field. The first field has number 0. Specifying a field number less than 0 and greater or equal the number of fields will trigger an error.
Returns the specification of the fieldno'th database
field as an associated array. The array contains three fields named
name, type, and
size.
(PECL paradox >= 1.0.0)
px_get_info — Return lots of information about a paradox file
$pxdoc
) : arrayReturns an associated array with lots of information about a paradox file. This array is likely to be extended in the future.
Version of file multiplied by 10, e.g. 70.
Name of table as stored in the file. If the database was created by pxlib, then this will be the name of the file without the extension.
Number of records in this table.
Number of fields in this table.
Number of bytes used for the header. This is usually 0x800.
Number of bytes used for each record. This is the sum of all field sizes (available since version 1.4.2).
This value multiplied by 0x400 is the size of a data block in bytes. The maximum number of records in a datablock is the integer part of (maxtablesize * 0x400 - 8) / recordsize.
The number of data blocks in the file. Each data block contains a certain number of records which depends on the record size and the data block size (maxtablesize). Data blocks may not necessarily be completely filled.
Number of fields used for the primary index. The fields do always start with field number 1.
The DOS codepage which was used for encoding fields with character data. If the target encoding is not set with px_set_targetencoding() this will be the encoding for character fields when records are being accessed with px_get_record() or px_retrieve_record().
(PECL paradox >= 1.1.0)
px_get_parameter — Gets a parameter
$pxdoc
, string $name
) : stringGets various parameters.
pxdocResource identifier of the paradox database as returned by px_new().
name
The name can be one of the following:
The name of the table as it will be stored in the database header.
The encoding for the output. Data which is being read from character fields with px_get_record() or px_retrieve_record() is recoded into the targetencoding. If it is not set, then the data will be delivered as stored in the database file.
The encoding of the input data which is to be stored into the database. When storing data of character fields in the database, the data is expected to be delivered in this encoding.
Returns the value of the parameter or FALSE on failure.
(PECL paradox >= 1.0.0)
px_get_record — Returns record of paradox database
$pxdoc
, int $num
[, int $mode = 0
] ) : array
pxdocResource identifier of the paradox database as returned by px_new().
numThe record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.
mode
The optional mode can be
PX_KEYTOLOWER or PX_KEYTOUPPER
in order to convert the keys of the returned array into lower or
upper case. If
mode is not passed or is 0, then the key will be
exactly like the field name. The element values will contain the field
values. NULL values will be retained and are different from 0.0, 0 or
the empty string. Fields of type PX_FIELD_TIME
will be returned as an integer counting the number of milliseconds
starting at midnight. A timestamp
(PX_FIELD_TIMESTAMP) and date
(PX_FIELD_DATE) are floating point respectively
int values counting milliseconds respectively days starting
at the beginning of julian calendar.
Use the functions px-timestamp2string() and
px-date2string() to convert them into a character
representation.
Returns the num'th record from the paradox
database. The record is returned as an associated array with its keys
being the field names.
(PECL paradox >= 1.0.0)
px_get_schema — Returns the database schema
$pxdoc
[, int $mode = 0
] ) : arraypx_get_schema() returns the database schema.
pxdocResource identifier of the paradox database as returned by px_new().
mode
If the optional mode is
PX_KEYTOLOWER or
PX_KEYTOUPPER the keys of the returned array
will be converted to lower
or upper case. If mode is 0 or not passed at all,
then the key name will be identical to the field name.
Returns the schema of a database file as an associated array. The key name
is equal to the field name. Each array element is itself an associated
array containing the two fields type and
size. type is one of the constants in
table Constants for field
types. size is the number of bytes this field
consumes in the record. The total of all field sizes is equal to the
record size as it can be retrieved with px-get-info().
(PECL paradox >= 1.1.0)
px_get_value — Gets a value
$pxdoc
, string $name
) : floatGets various values.
pxdocResource identifier of the paradox database as returned by px_new().
name
name can be one of the following.
The number of primary keys. Paradox databases always use the
first numprimkeys fields for the primary
index.
Returns the value of the parameter or FALSE on failure.
(PECL paradox >= 1.4.0)
px_insert_record — Inserts record into paradox database
$pxdoc
, array $data
) : intInserts a new record into the database. The record is not necessarily inserted at the end of the database, but may be inserted at any position depending on where the first free slot is found.
The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.
Most field values can be passed as its equivalent php type e.g. a long value is used for fields of type PX_FIELD_LONG, PX_FIELD_SHORT and PX_FIELD_AUTOINC, a double values is used for fields of type PX_FIELD_CURRENCY and PX_FIELD_NUMBER. Field values for blob and alpha fields are passed as strings.
Fields of type PX_FIELD_TIME and PX_FIELD_DATE both require a long value. In the first case this is the number of milliseconds since midnight. In the second case this is the number of days since 1.1.0000. Below there are two examples to convert the current date or timestamp into a value suitable for one of paradox's date/time fields.
Note:
This function is only available if pxlib >= 0.6.0 is used.
pxdocResource identifier of the paradox database as returned by px_new().
dataAssociated or indexed array containing the field values as e.g. returned by px_retrieve_record().
Returns FALSE on failure or the record number in case of success.
Example #1 Set the date/time fields in a paradox database to the current date/time
<?php
$px = px_new();
$fp = fopen("test.db", "w+");
px_create_fp($px, $fp, array(array("timestamp", "@"), array("time", "T"), array("date", "D")));
$curdate = getdate();
$jd = gregoriantojd($curdate["mon"], $curdate["mday"], $curdate["year"]);
$days = $jd - 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
$secs = $curdate["hours"]*3600 + $curdate["minutes"]*60 + $curdate["seconds"];
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));
$curtimestamp = microtime(true);
$days = (int) ($curtimestamp/86400);
$secs = $curtimestamp - ($days * 86400.0);
$days += 2440588; /* Number of days between 1.1.4714 b.c. and 1.1.1970 */
$days -= 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));
for($i=0; $i<2; $i++) {
$rec = px_retrieve_record($px, $i);
echo px_timestamp2string($px, $rec["timestamp"], "n/d/Y H:i:s")."\n";
echo px_date2string($px, $rec["date"], "n/d/Y")."\n";
}
px_close($px);
px_delete($px);
?>
The above example will output:
2/21/2006 21:42:30 2/21/2006 2/21/2006 20:42:30 2/21/2006
The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain milli seconds.
px_update_record() - Updates record in paradox database
(PECL paradox >= 1.0.0)
px_new — Create a new paradox object
Create a new paradox object. You will have to call this function before any
further functions. px_new() does not create any file on
the disk, it just creates an instance of a paradox object. This function
must not be called if the object oriented interface is used. Use new
paradox_db() instead.
Returns FALSE on failure.
Example #1 Opening a Paradox database
<?php
if(!$pxdoc = px_new()) {
/* Error handling */
}
$fp = fopen("test.db", "r");
if(!px_open_fp($pxdoc, $fp)) {
/* Error handling */
}
// ...
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>
If you prefer the object oriented API, then the above example will look like the following.
Example #2 Opening a Paradox database
<?php
$fp = fopen("test.db", "r");
$pxdoc = new paradox_db();
if(!$pxdoc->open_fp($fp)) {
/* Error handling */
}
// ...
$pxdoc->close();
fclose($fp);
?>
(PECL paradox >= 1.0.0)
px_numfields — Returns number of fields in a database
$pxdoc
) : intGet the number of fields in a database file.
Returns the number of fields in a database file. The return value of this
function is identical to the element numfields in the
array returned by px_get_info().
(PECL paradox >= 1.0.0)
px_numrecords — Returns number of records in a database
$pxdoc
) : intGet the number of records in a database file.
Returns the number of records in a database file. The return value of this
function is identical to the element numrecords in the
array returned by px_get_info().
(PECL paradox >= 1.0.0)
px_open_fp — Open paradox database
$pxdoc
, resource $file
) : boolOpen an existing paradox database file. The actual file has to be opened before with fopen(). This function can also be used to open primary index files and tread them like a paradox database. This is supported for those who would like to investigate a primary index. It cannot be used to accelerate access to a database file.
Returns TRUE on success or FALSE on failure.
(PECL paradox >= 1.0.0)
px_put_record — Stores record into paradox database
$pxdoc
, array $record
[, int $recpos = -1
] ) : boolStores a record into a paradox database. The record is always added at the end of the database, regardless of any free slots. Use px_insert_record() to add a new record into the first free slot found in the database.
pxdocResource identifier of the paradox database as returned by px_new().
recordAssociated or indexed array containing the field values as e.g. returned by px_retrieve_record().
recposThis optional parameter may be used to specify a record number greater than the current number of records in the database. The function will add as many empty records as needed. There is hardly any need for this parameter.
Returns TRUE on success or FALSE on failure.
(PECL paradox >= 1.4.0)
px_retrieve_record — Returns record of paradox database
$pxdoc
, int $num
[, int $mode = 0
] ) : arrayThis function is very similar to px_get_record() but uses internally a different approach to retrieve the data. It relies on pxlib for reading each single field value, which usually results in support for more field types.
Note:
This function is only available if pxlib >= 0.6.0 is used.
pxdocResource identifier of the paradox database as returned by px_new().
numThe record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.
mode
The optional mode can be
PX_KEYTOLOWER or PX_KEYTOUPPER
in order to convert the keys into lower or upper case. If
mode is not passed or is 0, then the key will be
exactly like the field name. The element values will contain the field
values. NULL values will be retained and are different from 0.0, 0 or
the empty string. Fields of type PX_FIELD_TIME
will be returned as an integer counting the number of milliseconds
starting at midnight. A timestamp is a floating point value also
counting milliseconds starting at the beginning of julian calendar.
Returns the num'th record from the paradox
database. The record is returned as an associated array with its keys
being the field names.
(PECL paradox >= 1.3.0)
px_set_blob_file — Sets the file where blobs are read from
$pxdoc
, string $filename
) : boolSets the name of the file where blobs are going to be read from or written into. Without calling this function, px_get_record() or px_retrieve_record() will only return data in blob fields if the data is part of the record and not stored in the blob file. Blob data is stored in the record if it is small enough to fit in the size of the blob field.
Calling px_put_record(), px_insert_record(), or px_update_record() without calling px_set_blob_file() will result in truncated blob fields unless the data fits into the database file.
Calling this function twice will close the first blob file and open the new one.
pxdocResource identifier of the paradox database as returned by px_new().
filename
The name of the file. Its extension should be .MB.
Returns TRUE on success or FALSE on failure.
(PECL paradox >= 1.1.0)
px_set_parameter — Sets a parameter
$pxdoc
, string $name
, string $value
) : boolSets various parameters.
pxdocResource identifier of the paradox database as returned by px_new().
name
Depending on the parameter you want to set, name
can be one of the following.
The name of the table as it will be stored in the database header.
The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.
The encoding of the input data which is to be stored into the database.
valueThe value of parameter to set. For inputencoding and targetencoding this must be the name of the encoding as understood by iconv or recode, e.g. iso-8859-1, utf-8, cp850.
Returns TRUE on success or FALSE on failure.
(PECL paradox >= 1.0.0)
px_set_tablename — Sets the name of a table (deprecated)
$pxdoc
, string $name
) : voidSets the table name of a paradox database, which was created with px_create_fp(). This function is deprecated use px_set_parameter() instead.
pxdocResource identifier of the paradox database as returned by px_new().
tablenameThe name of the table. If it is not set explicitly it will be set to the name of the database file.
Returns NULL on success or FALSE on failure.
px_set_parameter() - Sets a parameter
(PECL paradox >= 1.0.0)
px_set_targetencoding — Sets the encoding for character fields (deprecated)
$pxdoc
, string $encoding
) : bool
Set the encoding for data retrieved from a character field. All character
fields will be recoded to the encoding set by this function. If the
encoding is not set, the character data will be returned in the DOS code
page encoding as specified in the database file. The
encoding can be any string identifier known to
iconv or recode. On Unix systems run iconv -l for
a list of available encodings.
This function is deprecated and should be replaced by calling px_set_parameter().
See also px_get_info() to determine the DOS code page as stored in the database file.
pxdocResource identifier of the paradox database as returned by px_new().
encodingThe encoding for the output. Data which is being read from character fields is recoded into the targetencoding.
Returns FALSE if the encoding could not be set, e.g. the encoding is
unknown, or pxlib does not support recoding at all. In the second case a
warning will be issued.
px_set_parameter() - Sets a parameter
(PECL paradox >= 1.1.0)
px_set_value — Sets a value
$pxdoc
, string $name
, float $value
) : boolSets various values.
pxdocResource identifier of the paradox database as returned by px_new().
name
name can be one of the following.
The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.
value
Returns TRUE on success or FALSE on failure.
px_set_parameter() - Sets a parameter
(PECL paradox >= 1.4.0)
px_timestamp2string — Converts the timestamp into a string
$pxdoc
, float $value
, string $format
) : stringTurns a timestamp as it stored in the paradox file into human readable format. Paradox timestamps are the number of miliseconds since 0001-01-02. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the following example.
pxdocResource identifier of the paradox database.
valueValue as stored in paradox database field of type PX_FIELD_TIME, or PX_FIELD_TIMESTAMP.
formatString format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, H, h, G, g, i, s, A, a, L).
Returns TRUE on success or FALSE on failure.
Example #1 Turn a paradox timestamp into a human readable form
<?php
$px = px_new();
/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;
/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";
/* Turn it into a timestamp as it stored in a paradox database */
/* Timestamps are stored in miliseconds since 0001-01-02 */
$stamp = $days * 86400.0 * 1000.0;
/* Add one hour */
$stamp += 3600000.0;
/* The following will output '7/15/1917 01:00:00'. */
echo px_timestamp2string($px, $stamp, "n/d/Y H:i:s")."\n";
px_delete($px);
?>
The above example will output:
7/15/1917 7/15/1917 01:00:00
The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain miliseconds.
(PECL paradox >= 1.4.0)
px_update_record — Updates record in paradox database
$pxdoc
, array $data
, int $num
) : boolUpdates an exiting record in the database. The record starts at 0.
The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.
Note:
This function is only available if pxlib >= 0.6.0 is used.
pxdocResource identifier of the paradox database as returned by px_new().
dataAssociated array containing the field values as returned by px_retrieve_record().
numThe record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.
Returns TRUE on success or FALSE on failure.
px_insert_record() - Inserts record into paradox database
PostgreSQL database is an Open Source product and available without cost. Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases. It provides SQL92/SQL99 language support, transactions, referential integrity, stored procedures and type extensibility. PostgreSQL is an open source descendant of this original Berkeley code.
To use PostgreSQL support, you need PostgreSQL 6.5 or later, PostgreSQL 8.0 or later to enable all PostgreSQL module features. PostgreSQL supports many character encodings including multibyte character encoding. The current version and more information about PostgreSQL is available at » http://www.postgresql.org/ and the » PostgreSQL Documentation.
In order to enable PostgreSQL support,
--with-pgsql[=DIR] is required when you compile
PHP. DIR is the PostgreSQL base install directory, defaults to
/usr/local/pgsql. If shared object module is
available, PostgreSQL module may be loaded using
extension directive in php.ini or
dl()
function.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| pgsql.allow_persistent | "1" | PHP_INI_SYSTEM | |
| pgsql.max_persistent | "-1" | PHP_INI_SYSTEM | |
| pgsql.max_links | "-1" | PHP_INI_SYSTEM | |
| pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.2.0. |
| pgsql.ignore_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
| pgsql.log_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
Here's a short explanation of the configuration directives.
pgsql.allow_persistent
boolean
Whether to allow persistent Postgres connections.
pgsql.max_persistent
integer
The maximum number of persistent Postgres connections per process.
pgsql.max_links
integer
The maximum number of Postgres connections per process, including persistent connections.
pgsql.auto_reset_persistent
integer
Detect broken persistent links with pg_pconnect(). Needs a little overhead.
pgsql.ignore_notice
integer
Whether or not to ignore PostgreSQL backend notices.
pgsql.log_notice
integer
Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.
There are two resource types used in the PostgreSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
PGSQL_LIBPQ_VERSION
(string)
PGSQL_LIBPQ_VERSION_STR
(string)
PGSQL_ASSOC
(integer)
PGSQL_NUM
(integer)
PGSQL_BOTH
(integer)
PGSQL_CONNECT_FORCE_NEW
(integer)
PGSQL_CONNECT_ASYNC
(integer)
PGSQL_CONNECTION_AUTH_OK
(integer)
PGSQL_CONNECTION_AWAITING_RESPONSE
(integer)
PGSQL_CONNECTION_BAD
(integer)
PGSQL_CONNECTION_MADE
(integer)
PGSQL_CONNECTION_OK
(integer)
PGSQL_CONNECTION_SETENV
(integer)
PGSQL_CONNECTION_SSL_STARTUP
(integer)
PGSQL_CONNECTION_STARTED
(integer)
PGSQL_SEEK_SET
(integer)
PGSQL_SEEK_CUR
(integer)
PGSQL_SEEK_END
(integer)
PGSQL_EMPTY_QUERY
(integer)
PGSQL_COMMAND_OK
(integer)
PGSQL_TUPLES_OK
(integer)
SELECT or SHOW).
PGSQL_COPY_OUT
(integer)
PGSQL_COPY_IN
(integer)
PGSQL_BAD_RESPONSE
(integer)
PGSQL_NONFATAL_ERROR
(integer)
PGSQL_FATAL_ERROR
(integer)
PGSQL_TRANSACTION_IDLE
(integer)
PGSQL_TRANSACTION_ACTIVE
(integer)
PGSQL_TRANSACTION_INTRANS
(integer)
PGSQL_TRANSACTION_INERROR
(integer)
PGSQL_TRANSACTION_UNKNOWN
(integer)
PGSQL_DIAG_SEVERITY
(integer)
ERROR,
FATAL, or PANIC (in an error message), or
WARNING, NOTICE, DEBUG,
INFO, or LOG (in a notice message), or a localized
translation of one of these. Always present.
PGSQL_DIAG_SQLSTATE
(integer)
PGSQL_DIAG_MESSAGE_PRIMARY
(integer)
PGSQL_DIAG_MESSAGE_DETAIL
(integer)
PGSQL_DIAG_MESSAGE_HINT
(integer)
PGSQL_DIAG_STATEMENT_POSITION
(integer)
PGSQL_DIAG_INTERNAL_POSITION
(integer)
PG_DIAG_STATEMENT_POSITION field, but
it is used when the cursor position refers to an internally generated
command rather than the one submitted by the client. The
PG_DIAG_INTERNAL_QUERY field will always appear when this
field appears.
PGSQL_DIAG_INTERNAL_QUERY
(integer)
PGSQL_DIAG_CONTEXT
(integer)
PGSQL_DIAG_SOURCE_FILE
(integer)
PGSQL_DIAG_SOURCE_LINE
(integer)
PGSQL_DIAG_SOURCE_FUNCTION
(integer)
PGSQL_DIAG_SCHEMA_NAME
(string)
PGSQL_DIAG_TABLE_NAME
(string)
PGSQL_DIAG_COLUMN_NAME
(string)
PGSQL_DIAG_DATATYPE_NAME
(string)
PGSQL_DIAG_CONSTRAINT_NAME
(string)
PGSQL_ERRORS_TERSE
(integer)
PGSQL_ERRORS_DEFAULT
(integer)
PGSQL_ERRORS_VERBOSE
(integer)
PGSQL_NOTICE_LAST
(integer)
PGSQL_NOTICE_ALL
(integer)
PGSQL_NOTICE_CLEAR
(integer)
PGSQL_STATUS_LONG
(integer)
PGSQL_STATUS_STRING
(integer)
PGSQL_CONV_IGNORE_DEFAULT
(integer)
PGSQL_CONV_FORCE_NULL
(integer)
NULL in place of an empty string.
PGSQL_CONV_IGNORE_NOT_NULL
(integer)
NULL into SQL NOT NULL columns.
PGSQL_DML_NO_CONV
(integer)
PGSQL_DML_EXEC
(integer)
PGSQL_DML_ASYNC
(integer)
PGSQL_DML_STRING
(integer)
PGSQL_DML_ESCAPE
(integer)
PGSQL_POLLING_FAILED
(integer)
PGSQL_POLLING_READING
(integer)
PGSQL_POLLING_WRITING
(integer)
PGSQL_POLLING_OK
(integer)
PGSQL_POLLING_ACTIVE
(integer)
PGSQL_DIAG_SEVERITY_NONLOCALIZED
(integer)
This simple example shows how to connect, execute a query, print resulting rows and disconnect from a PostgreSQL database.
Example #1 PostgreSQL extension overview example
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
These examples contain user defined functions similar to legacy MySQL functions.
Example #1 PostgreSQL user defined functions example
<?php
// This function should be needed, since PostgreSQL connection binds database.
function pg_list_dbs($db)
{
assert(is_resource($db));
$query = '
SELECT
d.datname as "Name",
u.usename as "Owner",
pg_encoding_to_char(d.encoding) as "Encoding"
FROM
pg_database d LEFT JOIN pg_user u ON d.datdba = u.usesysid
ORDER BY 1;
';
return pg_query($db, $query);
}
// List tables.
function pg_list_tables($db)
{
assert(is_resource($db));
$query = "
SELECT
c.relname as \"Name\",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as \"Type\",
u.usename as \"Owner\"
FROM
pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
WHERE
c.relkind IN ('r','v','S','')
AND c.relname !~ '^pg_'
ORDER BY 1;
";
return pg_query($db, $query);
}
// See also pg_meta_data(). It returns field definition as array.
function pg_list_fields($db, $table)
{
assert(is_resource($db));
$query = "
SELECT
a.attname,
format_type(a.atttypid, a.atttypmod),
a.attnotnull,
a.atthasdef,
a.attnum
FROM
pg_class c,
pg_attribute a
WHERE
c.relname = '".$table."'
AND a.attnum > 0 AND a.attrelid = c.oid
ORDER BY a.attnum;
";
return pg_query($db, $query);
}
?>
Note:
Not all functions are supported by all builds. It depends on your libpq (The PostgreSQL C client library) version and how libpq is compiled. If PHP PostgreSQL extensions are missing, then it is because your libpq version does not support them.
Note:
Most PostgreSQL functions accept
connectionas the optional first parameter. If it is not provided, the last opened connection is used. If it doesn't exist, functions returnFALSE.
Note:
PostgreSQL automatically folds all identifiers (e.g. table/column names) to lower-case values at object creation time and at query time. To force the use of mixed or upper case identifiers, you must escape the identifier using double quotes ("").
Note:
PostgreSQL does not have special commands for fetching database schema information (eg. all the tables in the current database). Instead, there is a standard schema named
information_schemain PostgreSQL 7.4 and above containing system views with all the necessary information, in an easily queryable form. See the » PostgreSQL Documentation for full details.
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_affected_rows — Returns number of affected records (tuples)
$result
) : int
pg_affected_rows() returns the number of tuples
(instances/records/rows) affected by INSERT,
UPDATE, and DELETE
queries.
Since PostgreSQL 9.0 and above, the server returns the number of SELECTed rows. Older PostgreSQL return 0 for SELECT.
Note:
This function used to be called pg_cmdtuples().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
The number of rows affected by the query. If no tuple is affected, it will return 0.
Example #1 pg_affected_rows() example
<?php
$result = pg_query($conn, "INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')");
$cmdtuples = pg_affected_rows($result);
echo $cmdtuples . " tuples are affected.\n";
?>
The above example will output:
1 tuples are affected.
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_cancel_query — Cancel an asynchronous query
$connection
) : boolpg_cancel_query() cancels an asynchronous query sent with pg_send_query(), pg_send_query_params() or pg_send_execute(). You cannot cancel a query executed using pg_query().
connectionPostgreSQL database connection resource.
Returns TRUE on success or FALSE on failure.
Example #1 pg_cancel_query() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}
$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo "$res1 has $rows1 records\n\n";
// Cancel the currently running query. Will be the second query if it is
// still running.
pg_cancel_query($dbconn);
?>
The above example will output:
First call to pg_get_result(): Resource id #3 Resource id #3 has 3 records
(PHP 4 >= 4.0.3, PHP 5, PHP 7)
pg_client_encoding — Gets the client encoding
$connection
] ) : stringPostgreSQL supports automatic character set conversion between server and client for certain character sets. pg_client_encoding() returns the client encoding as a string. The returned string will be one of the standard PostgreSQL encoding identifiers.
Note:
This function requires PHP 4.0.3 or higher and PostgreSQL 7.0 or higher. If libpq is compiled without multibyte encoding support, pg_client_encoding() always returns
SQL_ASCII. Supported encoding depends on PostgreSQL version. Refer to the PostgreSQL Documentation supported encodings.The function used to be called pg_clientencoding().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
The client encoding, or FALSE on error.
Example #1 pg_client_encoding() example
<?php
// Assume $conn is a connection to a ISO-8859-1 database
$encoding = pg_client_encoding($conn);
echo "Client encoding is: ", $encoding, "\n";
?>
The above example will output:
Client encoding is: ISO-8859-1
(PHP 4, PHP 5, PHP 7)
pg_close — Closes a PostgreSQL connection
$connection
] ) : bool
pg_close() closes the non-persistent
connection to a PostgreSQL database associated with the given
connection resource.
Note:
Using pg_close() is not usually necessary, as non-persistent open connections are automatically closed at the end of the script.
If there is open large object resource on the connection, do not close the connection before closing all large object resources.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
Returns TRUE on success or FALSE on failure.
Example #1 pg_close() example
<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
or die("Could not connect");
echo "Connected successfully";
pg_close($dbconn);
?>
The above example will output:
Connected successfully
(PHP 5 >= 5.6.0, PHP 7)
pg_connect_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt
$connection
) : int
pg_connect_poll() polls the status of a PostgreSQL
connection created by calling pg_connect() with the
PGSQL_CONNECT_ASYNC option.
connectionPostgreSQL database connection resource.
Returns PGSQL_POLLING_FAILED,
PGSQL_POLLING_READING,
PGSQL_POLLING_WRITING,
PGSQL_POLLING_OK, or
PGSQL_POLLING_ACTIVE.
(PHP 4, PHP 5, PHP 7)
pg_connect — Open a PostgreSQL connection
$connection_string
[, int $connect_type
] ) : resource
pg_connect() opens a connection to a
PostgreSQL database specified by the
connection_string.
If a second call is made to pg_connect() with
the same connection_string as an existing connection, the
existing connection will be returned unless you pass
PGSQL_CONNECT_FORCE_NEW as
connect_type.
The old syntax with multiple parameters $conn = pg_connect("host", "port", "options", "tty", "dbname") has been deprecated.
connection_string
The connection_string can be empty to use all default parameters, or it
can contain one or more parameter settings separated by whitespace.
Each parameter setting is in the form keyword = value. Spaces around
the equal sign are optional. To write an empty value or a value
containing spaces, surround it with single quotes, e.g., keyword =
'a value'. Single quotes and backslashes within the value must be
escaped with a backslash, i.e., \' and \\.
The currently recognized parameter keywords are:
host, hostaddr, port,
dbname (defaults to value of user),
user,
password, connect_timeout,
options, tty (ignored), sslmode,
requiressl (deprecated in favor of sslmode), and
service. Which of these arguments exist depends
on your PostgreSQL version.
The options parameter can be used to set command line parameters
to be invoked by the server.
connect_type
If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection
is created, even if the connection_string is identical to
an existing connection.
If PGSQL_CONNECT_ASYNC is given, then the
connection is established asynchronously. The state of the connection
can then be checked via pg_connect_poll() or
pg_connection_status().
PostgreSQL connection resource on success, FALSE on failure.
| Version | Description |
|---|---|
| 5.6.0 |
Support for giving the PGSQL_CONNECT_ASYNC
constant as the connect_type was added.
|
Example #1 Using pg_connect()
<?php
$dbconn = pg_connect("dbname=mary");
//connect to a database named "mary"
$dbconn2 = pg_connect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"
$dbconn3 = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password
$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
$dbconn5 = pg_connect("host=localhost options='--client_encoding=UTF8'");
//connect to a database on "localhost" and set the command line parameter which tells the encoding is in UTF-8
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_connection_busy — Get connection is busy or not
$connection
) : boolpg_connection_busy() determines whether or not a connection is busy. If it is busy, a previous query is still executing. If pg_get_result() is used on the connection, it will be blocked.
connectionPostgreSQL database connection resource.
Returns TRUE if the connection is busy, FALSE otherwise.
Example #1 pg_connection_busy() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$bs = pg_connection_busy($dbconn);
if ($bs) {
echo 'connection is busy';
} else {
echo 'connection is not busy';
}
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_connection_reset — Reset connection (reconnect)
$connection
) : boolpg_connection_reset() resets the connection. It is useful for error recovery.
connectionPostgreSQL database connection resource.
Returns TRUE on success or FALSE on failure.
Example #1 pg_connection_reset() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$dbconn2 = pg_connection_reset($dbconn);
if ($dbconn2) {
echo "reset successful\n";
} else {
echo "reset failed\n";
}
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_connection_status — Get connection status
$connection
) : int
pg_connection_status() returns the status of
the specified connection.
connectionPostgreSQL database connection resource.
PGSQL_CONNECTION_OK or
PGSQL_CONNECTION_BAD.
Example #1 pg_connection_status() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$stat = pg_connection_status($dbconn);
if ($stat === PGSQL_CONNECTION_OK) {
echo 'Connection status ok';
} else {
echo 'Connection status bad';
}
?>
(PHP 5 >= 5.6.0, PHP 7)
pg_consume_input — Reads input on the connection
$connection
) : boolpg_consume_input() consumes any input waiting to be read from the database server.
connectionPostgreSQL database connection resource.
TRUE if no error occurred, or FALSE if there was an error. Note that
TRUE does not necessarily indicate that input was waiting to be read.
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_convert — Convert associative array values into forms suitable for SQL statements
$connection
, string $table_name
, array $assoc_array
[, int $options = 0
] ) : array
pg_convert() checks and converts the values in
assoc_array into suitable values for use in an SQL
statement. Precondition for pg_convert() is the
existence of a table table_name which has at least
as many columns as assoc_array has elements. The
fieldnames in table_name must match the indices in
assoc_array and the corresponding datatypes must be
compatible. Returns an array with the converted values on success, FALSE
otherwise.
Note:
Since PHP 5.6.0, it accepts boolean values, converting them to PostgreSQL booleans. String representations of boolean values are also supported.
NULLis converted to PostgreSQL NULL.Prior to PHP 5.6.0, if there are boolean fields in
table_namedon't use the constantTRUEinassoc_array. It will be converted to the string 'TRUE' which is not a valid entry for boolean fields in PostgreSQL. Use one of "t", "true", 1, "y", "yes" instead.
connectionPostgreSQL database connection resource.
table_nameName of the table against which to convert types.
assoc_arrayData to be converted.
options
Any number of PGSQL_CONV_IGNORE_DEFAULT,
PGSQL_CONV_FORCE_NULL or
PGSQL_CONV_IGNORE_NOT_NULL, combined.
An array of converted values, or FALSE on error.
Example #1 pg_convert() example
<?php
$dbconn = pg_connect('dbname=foo');
$tmp = array(
'author' => 'Joe Thackery',
'year' => 2005,
'title' => 'My Life, by Joe Thackery'
);
$vals = pg_convert($dbconn, 'authors', $tmp);
?>
| Version | Description |
|---|---|
| 5.6.0 | No longer experimental. Boolean/NULL data types are supported. Unknown/unsupported data types are escaped without validation. pg_convert() can be used with any data types. |
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_copy_from — Insert records into a table from an array
$connection
, string $table_name
, array $rows
[, string $delimiter
[, string $null_as
]] ) : bool
pg_copy_from() inserts records into a table from
rows. It issues a COPY FROM SQL command
internally to insert records.
connectionPostgreSQL database connection resource.
table_name
Name of the table into which to copy the rows.
rows
An array of data to be copied into table_name.
Each value in rows becomes a row in table_name.
Each value in rows should be a delimited string of the values
to insert into each field. Values should be linefeed terminated.
delimiter
The token that separates values for each field in each element of
rows. Default is TAB.
null_as
How SQL NULL values are represented in the
rows. Default is \N ("\\N").
Returns TRUE on success or FALSE on failure.
Example #1 pg_copy_from() example
<?php
$db = pg_connect("dbname=publisher") or die("Could not connect");
$rows = pg_copy_to($db, $table_name);
pg_query($db, "DELETE FROM $table_name");
pg_copy_from($db, $table_name, $rows);
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_copy_to — Copy a table to an array
$connection
, string $table_name
[, string $delimiter
[, string $null_as
]] ) : array
pg_copy_to() copies a table to an array. It
issues COPY TO SQL command internally to
retrieve records.
connectionPostgreSQL database connection resource.
table_name
Name of the table from which to copy the data into rows.
delimiter
The token that separates values for each field in each element of
rows. Default is TAB.
null_as
How SQL NULL values are represented in the
rows. Default is \N ("\\N").
An array with one element for each line of COPY data.
It returns FALSE on failure.
Example #1 pg_copy_to() example
<?php
$db = pg_connect("dbname=publisher") or die("Could not connect");
$rows = pg_copy_to($db, $table_name);
pg_query($db, "DELETE FROM $table_name");
pg_copy_from($db, $table_name, $rows);
?>
(PHP 4, PHP 5, PHP 7)
pg_dbname — Get the database name
$connection
] ) : string
pg_dbname() returns the name of the database
that the given PostgreSQL connection
resource.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
A string containing the name of the database the
connection is to, or FALSE on error.
Example #1 pg_dbname() example
<?php
error_reporting(E_ALL);
pg_connect("host=localhost port=5432 dbname=mary");
echo pg_dbname(); // mary
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_delete — Deletes records
$connection
, string $table_name
, array $assoc_array
[, int $options = PGSQL_DML_EXEC
] ) : mixed
pg_delete() deletes records from a table
specified by the keys and values
in assoc_array. If options
is specified, pg_convert() is applied
to assoc_array with the specified options.
If options is specified,
pg_convert() is applied to
assoc_array with the specified flags.
By default pg_delete() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes parameters/identifiers. Therefore, table/column names became case sensitive.
Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.
connectionPostgreSQL database connection resource.
table_nameName of the table from which to delete rows.
assoc_array
An array whose keys are field names in the table table_name,
and whose values are the values of those fields that are to be deleted.
options
Any number of PGSQL_CONV_FORCE_NULL,
PGSQL_DML_NO_CONV,
PGSQL_DML_ESCAPE,
PGSQL_DML_EXEC,
PGSQL_DML_ASYNC or
PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the
options then query string is returned. When PGSQL_DML_NO_CONV
or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.
Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed
via options.
Example #1 pg_delete() example
<?php
$db = pg_connect('dbname=foo');
// This is safe somewhat, since all values are escaped.
// However PostgreSQL supports JSON/Array. These are not
// safe by neither escape nor prepared query.
$res = pg_delete($db, 'post_log', $_POST);
if ($res) {
echo "POST data is deleted: $res\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>
| Version | Description |
|---|---|
| 5.6.0 |
No longer experimental. Added PGSQL_DML_ESCAPE constant,
TRUE/FALSE and NULL data type support.
|
| 5.5.3/5.4.19 |
Direct SQL injection to table_name and Indirect SQL
injection to identifiers are fixed.
|
(PHP 4 >= 4.0.3, PHP 5, PHP 7)
pg_end_copy — Sync with PostgreSQL backend
$connection
] ) : boolpg_end_copy() syncs the PostgreSQL frontend (usually a web server process) with the PostgreSQL server after doing a copy operation performed by pg_put_line(). pg_end_copy() must be issued, otherwise the PostgreSQL server may get out of sync with the frontend and will report an error.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
Returns TRUE on success or FALSE on failure.
Example #1 pg_end_copy() example
<?php
$conn = pg_pconnect("dbname=foo");
pg_query($conn, "create table bar (a int4, b char(16), d float8)");
pg_query($conn, "copy bar from stdin");
pg_put_line($conn, "3\thello world\t4.5\n");
pg_put_line($conn, "4\tgoodbye world\t7.11\n");
pg_put_line($conn, "\\.\n");
pg_end_copy($conn);
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_escape_bytea — Escape a string for insertion into a bytea field
$connection
], string $data
) : stringpg_escape_bytea() escapes string for bytea datatype. It returns escaped string.
Note:
When you
SELECTa bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e.
INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea);PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
dataA string containing text or binary data to be inserted into a bytea column.
A string containing the escaped data.
| Version | Description |
|---|---|
| 5.2.0 | connection added |
Example #1 pg_escape_bytea() example
<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Read in a binary file
$data = file_get_contents('image1.jpg');
// Escape the binary data
$escaped = pg_escape_bytea($data);
// Insert it into the database
pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '{$escaped}')");
?>
(PHP 5 >= 5.4.4, PHP 7)
pg_escape_identifier — Escape a identifier for insertion into a text field
$connection
], string $data
) : stringpg_escape_identifier() escapes a identifier (e.g. table, field names) for querying the database. It returns an escaped identifier string for PostgreSQL server. pg_escape_identifier() adds double quotes before and after data. Users should not add double quotes. Use of this function is recommended for identifier parameters in query. For SQL literals (i.e. parameters except bytea), pg_escape_literal() or pg_escape_string() must be used. For bytea type fields, pg_escape_bytea() must be used instead.
Note:
This function has internal escape code and can also be used with PostgreSQL 8.4 or less.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
dataA string containing text to be escaped.
A string containing the escaped data.
Example #1 pg_escape_identifier() example
<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Escape the table name data
$escaped = pg_escape_identifier($table_name);
// Select rows from $table_name
pg_query("SELECT * FROM {$escaped};");
?>
(PHP 5 >= 5.4.4, PHP 7)
pg_escape_literal — Escape a literal for insertion into a text field
$connection
], string $data
) : stringpg_escape_literal() escapes a literal for querying the PostgreSQL database. It returns an escaped literal in the PostgreSQL format. pg_escape_literal() adds quotes before and after data. Users should not add quotes. Use of this function is recommended instead of pg_escape_string(). If the type of the column is bytea, pg_escape_bytea() must be used instead. For escaping identifiers (e.g. table, field names), pg_escape_identifier() must be used.
Note:
This function has internal escape code and can also be used with PostgreSQL 8.4 or less.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
When there is no default connection, it raises E_WARNING
and returns FALSE.
dataA string containing text to be escaped.
A string containing the escaped data.
Example #1 pg_escape_literal() example
<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Read in a text file (containing apostrophes and backslashes)
$data = file_get_contents('letter.txt');
// Escape the text data
$escaped = pg_escape_literal($data);
// Insert it into the database. Note that no quotes around {$escaped}
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', {$escaped})");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_escape_string — Escape a string for query
$connection
], string $data
) : stringpg_escape_string() escapes a string for querying the database. It returns an escaped string in the PostgreSQL format without quotes. pg_escape_literal() is more preferred way to escape SQL parameters for PostgreSQL. addslashes() must not be used with PostgreSQL. If the type of the column is bytea, pg_escape_bytea() must be used instead. pg_escape_identifier() must be used to escape identifiers (e.g. table names, field names)
Note:
This function requires PostgreSQL 7.2 or later.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
dataA string containing text to be escaped.
A string containing the escaped data.
| Version | Description |
|---|---|
| 5.2.0 | connection added |
Example #1 pg_escape_string() example
<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Read in a text file (containing apostrophes and backslashes)
$data = file_get_contents('letter.txt');
// Escape the text data
$escaped = pg_escape_string($data);
// Insert it into the database
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?>
(PHP 5 >= 5.1.0, PHP 7)
pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result
$connection
], string $stmtname
, array $params
) : resourceSends a request to execute a prepared statement with given parameters, and waits for the result.
pg_execute() is like pg_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. pg_execute() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.
The parameters are identical to pg_query_params(), except that the name of a prepared statement is given instead of a query string.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
stmtname
The name of the prepared statement to execute. if
"" is specified, then the unnamed statement is executed. The name must have
been previously prepared using pg_prepare(),
pg_send_prepare() or a PREPARE SQL
command.
paramsAn array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.
Elements are converted to strings by calling this function.
A query result resource on success or FALSE on failure.
Example #1 Using pg_execute()
<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
?>
(PHP 5 >= 5.1.0, PHP 7)
pg_fetch_all_columns — Fetches all rows in a particular result column as an array
$result
[, int $column = 0
] ) : arraypg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the result resource.
Note: This function sets NULL fields to the PHP
NULLvalue.
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
columnColumn number, zero-based, to be retrieved from the result resource. Defaults to the first column if not specified.
An array with all values in the result column.
FALSE is returned if column is larger than the number
of columns in the result, or on any other error.
Example #1 pg_fetch_all_columns() example
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);
var_dump($arr);
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_fetch_all — Fetches all rows from a result as an array
$result
[, int $result_type = PGSQL_ASSOC
] ) : arraypg_fetch_all() returns an array that contains all rows (records) in the result resource.
Note: This function sets NULL fields to the PHP
NULLvalue.
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
An array with all rows in the result. Each row is an array of field values indexed by field name.
FALSE is returned if there are no rows in the result, or on any
other error.
Example #1 PostgreSQL fetch all
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
$arr = pg_fetch_all($result);
print_r($arr);
?>
The above example will output something similar to:
Array
(
[0] => Array
(
[id] => 1
[name] => Fred
)
[1] => Array
(
[id] => 2
[name] => Bob
)
)
| Version | Description |
|---|---|
| 7.1.0 |
The result_type parameter was added.
|
(PHP 4, PHP 5, PHP 7)
pg_fetch_array — Fetch a row as an array
$result
[, int $row
[, int $result_type = PGSQL_BOTH
]] ) : arraypg_fetch_array() returns an array that corresponds to the fetched row (record).
pg_fetch_array() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field number) to the result array, it can also store the data using associative indices (field name). It stores both indices by default.
Note: This function sets NULL fields to the PHP
NULLvalue.
pg_fetch_array() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards. If
omitted or NULL, the next row is fetched.
result_type
An optional parameter that controls
how the returned array is indexed.
result_type is a constant and can take the
following values: PGSQL_ASSOC,
PGSQL_NUM and PGSQL_BOTH.
Using PGSQL_NUM, pg_fetch_array()
will return an array with numerical indices, using
PGSQL_ASSOC it will return only associative indices
while PGSQL_BOTH, the default, will return both
numerical and associative indices.
An array indexed numerically (beginning with 0) or
associatively (indexed by field name), or both.
Each value in the array is represented as a
string. Database NULL
values are returned as NULL.
FALSE is returned if row exceeds the number
of rows in the set, there are no more rows, or on any other error.
Example #1 pg_fetch_array() example
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " <- Row 1 Author\n";
echo $arr[1] . " <- Row 1 E-mail\n";
// The row parameter is optional; NULL can be passed instead,
// to pass a result_type. Successive calls to pg_fetch_array
// will return the next row.
$arr = pg_fetch_array($result, NULL, PGSQL_ASSOC);
echo $arr["author"] . " <- Row 2 Author\n";
echo $arr["email"] . " <- Row 2 E-mail\n";
$arr = pg_fetch_array($result);
echo $arr["author"] . " <- Row 3 Author\n";
echo $arr[1] . " <- Row 3 E-mail\n";
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_fetch_assoc — Fetch a row as an associative array
$result
[, int $row
] ) : arraypg_fetch_assoc() returns an associative array that corresponds to the fetched row (records).
pg_fetch_assoc() is equivalent to calling
pg_fetch_array() with PGSQL_ASSOC as the
optional third parameter. It only returns an associative array.
If you need the numeric indices, use
pg_fetch_row().
Note: This function sets NULL fields to the PHP
NULLvalue.
pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards. If
omitted or NULL, the next row is fetched.
An array indexed associatively (by field name).
Each value in the array is represented as a
string. Database NULL
values are returned as NULL.
FALSE is returned if row exceeds the number
of rows in the set, there are no more rows, or on any other error.
Example #1 pg_fetch_assoc() example
<?php
$conn = pg_connect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_assoc($result)) {
echo $row['id'];
echo $row['author'];
echo $row['email'];
}
?>
(PHP 4, PHP 5, PHP 7)
pg_fetch_object — Fetch a row as an object
$result
[, int $row
[, int $result_type = PGSQL_ASSOC
]] ) : object$result
[, int $row
[, string $class_name
[, array $params
]]] ) : objectpg_fetch_object() returns an object with properties that correspond to the fetched row's field names. It can optionally instantiate an object of a specific class, and pass parameters to that class's constructor.
Note: This function sets NULL fields to the PHP
NULLvalue.
Speed-wise, the function is identical to pg_fetch_array(), and almost as fast as pg_fetch_row() (the difference is insignificant).
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards. If
omitted or NULL, the next row is fetched.
result_typeIgnored and deprecated.
class_nameThe name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.
params
An optional array of parameters to pass to the constructor
for class_name objects.
An object with one attribute for each field
name in the result. Database NULL
values are returned as NULL.
FALSE is returned if row exceeds the number
of rows in the set, there are no more rows, or on any other error.
Example #1 pg_fetch_object() example
<?php
$database = "store";
$db_conn = pg_connect("host=localhost port=5432 dbname=$database");
if (!$db_conn) {
echo "Failed connecting to postgres database $database\n";
exit;
}
$qu = pg_query($db_conn, "SELECT * FROM books ORDER BY author");
while ($data = pg_fetch_object($qu)) {
echo $data->author . " (";
echo $data->year . "): ";
echo $data->title . "<br />";
}
pg_free_result($qu);
pg_close($db_conn);
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_fetch_result — Returns values from a result resource
pg_fetch_result() returns the value of a particular row and field (column) in a PostgreSQL result resource.
Note:
This function used to be called pg_result().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
rowRow number in result to fetch. Rows are numbered from 0 upwards. If omitted, next row is fetched.
fieldA string representing the name of the field (column) to fetch, otherwise an int representing the field number to fetch. Fields are numbered from 0 upwards.
Boolean is returned as "t" or "f". All
other types, including arrays are returned as strings formatted
in the same default PostgreSQL manner that you would see in the
psql program. Database NULL
values are returned as NULL.
FALSE is returned if row exceeds the number
of rows in the set, or on any other error.
Example #1 pg_fetch_result() example
<?php
$db = pg_connect("dbname=users user=me") || die();
$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");
$val = pg_fetch_result($res, 1, 0);
echo "First field in the second row is: ", $val, "\n";
?>
The above example will output:
First field in the second row is: 2
(PHP 4, PHP 5, PHP 7)
pg_fetch_row — Get a row as an enumerated array
$result
[, int $row
] ) : array
pg_fetch_row() fetches one row of data from
the result associated with the specified
result resource.
Note: This function sets NULL fields to the PHP
NULLvalue.
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
row
Row number in result to fetch. Rows are numbered from 0 upwards. If
omitted or NULL, the next row is fetched.
An array, indexed from 0 upwards, with each value
represented as a string. Database NULL
values are returned as NULL.
FALSE is returned if row exceeds the number
of rows in the set, there are no more rows, or on any other error.
Example #1 pg_fetch_row() example
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_field_is_null — Test if a field is SQL NULL
pg_field_is_null() tests if a field in a PostgreSQL
result resource is SQL NULL or not.
Note:
This function used to be called pg_fieldisnull().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
rowRow number in result to fetch. Rows are numbered from 0 upwards. If omitted, current row is fetched.
fieldField number (starting from 0) as an integer or the field name as a string.
Returns 1 if the field in the given row is SQL NULL, 0
if not. FALSE is returned if the row is out of range, or upon any other error.
Example #1 pg_field_is_null() example
<?php
$dbconn = pg_connect("dbname=publisher") or die ("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
if ($res) {
if (pg_field_is_null($res, 0, "year") == 1) {
echo "The value of the field year is null.\n";
}
if (pg_field_is_null($res, 0, "year") == 0) {
echo "The value of the field year is not null.\n";
}
}
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_field_name — Returns the name of a field
$result
, int $field_number
) : string
pg_field_name() returns the name of the field
occupying the given field_number in the
given PostgreSQL result resource. Field
numbering starts from 0.
Note:
This function used to be called pg_fieldname().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
field_numberField number, starting from 0.
The field name, or FALSE on error.
Example #1 Getting information about fields
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>
The above example will output:
column 0 fieldname: author printed length: 6 characters storage length: -1 bytes field type: varchar column 1 fieldname: year printed length: 4 characters storage length: 2 bytes field type: int2 column 2 fieldname: title printed length: 24 characters storage length: -1 bytes field type: varchar
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_field_num — Returns the field number of the named field
$result
, string $field_name
) : int
pg_field_num() will return the number of the
field number that corresponds to the
field_name in the given PostgreSQL
result resource.
Note:
This function used to be called pg_fieldnum().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
field_nameThe name of the field.
The field number (numbered from 0), or -1 on error.
Example #1 Getting information about fields
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "select author, year, title from authors where author = 'Orwell'");
echo "Column 'title' is field number: ", pg_field_num($res, 'title');
?>
The above example will output:
Column 'title' is field number: 2
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_field_prtlen — Returns the printed length
pg_field_prtlen() returns the actual printed
length (number of characters) of a specific value in a PostgreSQL
result. Row numbering starts at 0. This
function will return FALSE on an error.
field_name_or_number can be passed either as an
integer or as a string. If it is passed as an
integer, PHP recognises it as the field number, otherwise as
field name.
See the example given at the pg_field_name() page.
Note:
This function used to be called pg_fieldprtlen().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
rowRow number in result. Rows are numbered from 0 upwards. If omitted, current row is fetched.
The field printed length, or FALSE on error.
Example #1 Getting information about fields
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>
The above example will output:
column 0 fieldname: author printed length: 6 characters storage length: -1 bytes field type: varchar column 1 fieldname: year printed length: 4 characters storage length: 2 bytes field type: int2 column 2 fieldname: title printed length: 24 characters storage length: -1 bytes field type: varchar
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_field_size — Returns the internal storage size of the named field
$result
, int $field_number
) : int
pg_field_size() returns the internal storage
size (in bytes) of the field number in the given PostgreSQL
result.
Note:
This function used to be called pg_fieldsize().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
field_numberField number, starting from 0.
The internal field storage size (in bytes). -1 indicates a variable
length field. FALSE is returned on error.
Example #1 Getting information about fields
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>
The above example will output:
column 0 fieldname: author printed length: 6 characters storage length: -1 bytes field type: varchar column 1 fieldname: year printed length: 4 characters storage length: 2 bytes field type: int2 column 2 fieldname: title printed length: 24 characters storage length: -1 bytes field type: varchar
(PHP 5 >= 5.2.0, PHP 7)
pg_field_table — Returns the name or oid of the tables field
pg_field_table() returns the name of the table that field
belongs to, or the table's oid if oid_only is TRUE.
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
field_numberField number, starting from 0.
oid_only
By default the tables name that field belongs to is returned but
if oid_only is set to TRUE, then the
oid will instead be returned.
On success either the fields table name or oid. Or, FALSE on failure.
Example #1 Getting table information about a field
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "SELECT bar FROM foo");
echo pg_field_table($res, 0);
echo pg_field_table($res, 0, true);
$res = pg_query($dbconn, "SELECT version()");
var_dump(pg_field_table($res, 0));
?>
The above example will output something similar to:
foo 14379580 bool(false)
Note:
Returning the oid is much faster than returning the table name because fetching the table name requires a query to the database system table.
(PHP 5 >= 5.1.0, PHP 7)
pg_field_type_oid — Returns the type ID (OID) for the corresponding field number
$result
, int $field_number
) : int
pg_field_type_oid() returns an integer containing the
OID of the base type of the given field_number in the
given PostgreSQL result resource.
You can get more information about the field type by querying PostgreSQL's
pg_type system table using the OID obtained with this function.
The PostgreSQL format_type() function will convert a
type OID into an SQL standard type name.
Note:
If the field uses a PostgreSQL domain (rather than a basic type), it is the OID of the domain's underlying type that is returned, rather than the OID of the domain itself.
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
field_numberField number, starting from 0.
The OID of the field's base type. FALSE is returned on error.
Example #1 Getting information about fields
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Assume 'title' is a varchar type
$res = pg_query($dbconn, "select title from authors where author = 'Orwell'");
echo "Title field type OID: ", pg_field_type_oid($res, 0);
?>
The above example will output:
Title field type OID: 1043
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_field_type — Returns the type name for the corresponding field number
$result
, int $field_number
) : string
pg_field_type() returns a string containing the
base type name of the given field_number in the
given PostgreSQL result resource.
Note:
If the field uses a PostgreSQL domain (rather than a basic type), it is the name of the domain's underlying type that is returned, rather than the name of the domain itself.
Note:
This function used to be called pg_fieldtype().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
field_numberField number, starting from 0.
A string containing the base name of the field's type, or FALSE
on error.
Example #1 Getting information about fields
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Assume 'title' is a varchar type
$res = pg_query($dbconn, "select title from authors where author = 'Orwell'");
echo "Title field type: ", pg_field_type($res, 0);
?>
The above example will output:
Title field type: varchar
(PHP 5 >= 5.6.0, PHP 7)
pg_flush — Flush outbound query data on the connection
pg_flush() flushes any outbound query data waiting to be sent on the connection.
connectionPostgreSQL database connection resource.
Returns TRUE if the flush was successful or no data was waiting to be
flushed, 0 if part of the pending data was flushed but
more remains or FALSE on failure.
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_free_result — Free result memory
$result
) : boolpg_free_result() frees the memory and data associated with the specified PostgreSQL query result resource.
This function need only be called if memory consumption during script execution is a problem. Otherwise, all result memory will be automatically freed when the script ends.
Note:
This function used to be called pg_freeresult().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
Returns TRUE on success or FALSE on failure.
Example #1 pg_free_result() example
<?php
$db = pg_connect("dbname=users user=me") || die();
$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");
$val = pg_fetch_result($res, 1, 0);
echo "First field in the second row is: ", $val, "\n";
pg_free_result($res);
?>
The above example will output:
First field in the second row is: 2
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_get_notify — Gets SQL NOTIFY message
$connection
[, int $result_type
] ) : array
pg_get_notify() gets notifications generated by a
NOTIFY SQL command. To receive notifications,
the LISTEN SQL command must be
issued.
connectionPostgreSQL database connection resource.
result_type
An optional parameter that controls
how the returned array is indexed.
result_type is a constant and can take the
following values: PGSQL_ASSOC,
PGSQL_NUM and PGSQL_BOTH.
Using PGSQL_NUM, pg_get_notify()
will return an array with numerical indices, using
PGSQL_ASSOC it will return only associative indices
while PGSQL_BOTH, the default, will return both
numerical and associative indices.
An array containing the NOTIFY message name and backend PID.
As of PHP 5.4.0 and if supported by the server, the array also contains the server version and the payload.
Otherwise if no NOTIFY is waiting, then FALSE is returned.
Example #1 PostgreSQL NOTIFY message
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
// Listen 'author_updated' message from other processes
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify) {
echo "No messages\n";
} else {
print_r($notify);
}
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_get_pid — Gets the backend's process ID
$connection
) : int
pg_get_pid() gets the backend's (database server
process) PID. The PID is useful to determine whether or not a NOTIFY
message received via pg_get_notify() is sent from another process
or not.
connectionPostgreSQL database connection resource.
The backend database process ID.
Example #1 PostgreSQL backend PID
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_get_result — Get asynchronous query result
$connection
] ) : resourcepg_get_result() gets the result resource from an asynchronous query executed by pg_send_query(), pg_send_query_params() or pg_send_execute().
pg_send_query() and the other asynchronous query functions can send multiple queries to a PostgreSQL server and pg_get_result() is used to get each query's results, one by one.
connectionPostgreSQL database connection resource.
The result resource, or FALSE if no more results are available.
Example #1 pg_get_result() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}
$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo "$res1 has $rows1 records\n\n";
$res2 = pg_get_result($dbconn);
echo "Second call to pg_get_result(): $res2\n";
$rows2 = pg_num_rows($res2);
echo "$res2 has $rows2 records\n";
?>
The above example will output:
First call to pg_get_result(): Resource id #3 Resource id #3 has 3 records Second call to pg_get_result(): Resource id #4 Resource id #4 has 1 records
(PHP 4, PHP 5, PHP 7)
pg_host — Returns the host name associated with the connection
$connection
] ) : string
pg_host() returns the host name of the given
PostgreSQL connection resource is
connected to.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
A string containing the name of the host the
connection is to, or FALSE on error.
Example #1 pg_host() example
<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_insert — Insert array into table
$connection
, string $table_name
, array $assoc_array
[, int $options = PGSQL_DML_EXEC
] ) : mixed
pg_insert() inserts the values
of assoc_array into the table specified
by table_name. If options
is specified, pg_convert() is applied
to assoc_array with the specified options.
If options is specified,
pg_convert() is applied to
assoc_array with the specified flags.
By default pg_insert() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes parameters/identifiers. Therefore, table/column names became case sensitive.
Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.
connectionPostgreSQL database connection resource.
table_name
Name of the table into which to insert rows. The table table_name must at least
have as many columns as assoc_array has elements.
assoc_array
An array whose keys are field names in the table table_name,
and whose values are the values of those fields that are to be inserted.
options
Any number of PGSQL_CONV_OPTS,
PGSQL_DML_NO_CONV,
PGSQL_DML_ESCAPE,
PGSQL_DML_EXEC,
PGSQL_DML_ASYNC or
PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the
options then query string is returned. When PGSQL_DML_NO_CONV
or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.
Returns the connection resource on success, or FALSE on failure. Returns string if PGSQL_DML_STRING is passed
via options.
Example #1 pg_insert() example
<?php
$dbconn = pg_connect('dbname=foo');
// This is safe somewhat, since all values are escaped.
// However PostgreSQL supports JSON/Array. These are not
// safe by neither escape nor prepared query.
$res = pg_insert($dbconn, 'post_log', $_POST, PG_DML_ESCAPE);
if ($res) {
echo "POST data is successfully logged\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>
| Version | Description |
|---|---|
| 5.6.0 |
Unless PGSQL_DML_STRING is passed, the function
now returns the connection resource instead of TRUE on success.
|
| 5.6.0 |
No longer experimental. Added PGSQL_DML_ESCAPE constant,
TRUE/FALSE and NULL data type support.
|
| 5.5.3/5.4.19 |
Direct SQL injection to table_name and Indirect SQL
injection to identifiers are fixed.
|
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_last_error — Get the last error message string of a connection
$connection
] ) : string
pg_last_error() returns the last error message
for a given connection.
Error messages may be overwritten by internal PostgreSQL (libpq) function calls. It may not return an appropriate error message if multiple errors occur inside a PostgreSQL module function.
Use pg_result_error(), pg_result_error_field(), pg_result_status() and pg_connection_status() for better error handling.
Note:
This function used to be called pg_errormessage().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
A string containing the last error message on the
given connection, or FALSE on error.
Example #1 pg_last_error() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Query that fails
$res = pg_query($dbconn, "select * from doesnotexist");
echo pg_last_error($dbconn);
?>
(PHP 4 >= 4.0.6, PHP 5, PHP 7)
pg_last_notice — Returns the last notice message from PostgreSQL server
pg_last_notice() returns the last notice
message from the PostgreSQL server on the specified
connection. The PostgreSQL server sends notice
messages in several cases, for instance when creating a SERIAL
column in a table.
With pg_last_notice(), you can avoid issuing useless queries by checking whether or not the notice is related to your transaction.
Notice message tracking can be set to optional by setting 1 for
pgsql.ignore_notice in php.ini.
Notice message logging can be set to optional by setting 0 for
pgsql.log_notice in php.ini.
Unless pgsql.ignore_notice is set
to 0, notice message cannot be logged.
connectionPostgreSQL database connection resource.
option
One of PGSQL_NOTICE_LAST (to return last notice),
PGSQL_NOTICE_ALL (to return all notices),
or PGSQL_NOTICE_CLEAR (to clear notices).
A string containing the last notice on the
given connection with
PGSQL_NOTICE_LAST,
an array with PGSQL_NOTICE_ALL,
a boolean with PGSQL_NOTICE_CLEAR,
or FALSE on error.
Example #1 pg_last_notice() example
<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
$res = pg_query("CREATE TABLE test (id SERIAL)");
$notice = pg_last_notice($pgsql_conn);
echo $notice;
?>
The above example will output:
CREATE TABLE will create implicit sequence "test_id_seq" for "serial" column "test.id"
| Version | Description |
|---|---|
| 7.1.0 |
The option parameter was added.
|
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_last_oid — Returns the last row's OID
$result
) : stringpg_last_oid() is used to retrieve the OID assigned to an inserted row.
OID field became an optional field from PostgreSQL 7.2 and will not be present by default in PostgreSQL 8.1. When the OID field is not present in a table, the programmer must use pg_result_status() to check for successful insertion.
To get the value of a SERIAL field in an inserted
row, it is necessary to use the PostgreSQL CURRVAL
function, naming the sequence whose last value is required. If the
name of the sequence is unknown, the pg_get_serial_sequence
PostgreSQL 8.0 function is necessary.
PostgreSQL 8.1 has a function LASTVAL that returns
the value of the most recently used sequence in the session. This avoids
the need for naming the sequence, table or column altogether.
Note:
This function used to be called pg_getlastoid().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
A string containing the OID assigned to the most recently inserted
row in the specified connection, or FALSE on error or
no available OID.
Example #1 pg_last_oid() example
<?php
// Connect to the database
pg_connect("dbname=mark host=localhost");
// Create a sample table
pg_query("CREATE TABLE test (a INTEGER) WITH OIDS");
// Insert some data into it
$res = pg_query("INSERT INTO test VALUES (1)");
$oid = pg_last_oid($res);
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_close — Close a large object
$large_object
) : bool
pg_lo_close() closes a large
object. large_object is a resource for the
large object from pg_lo_open().
To use the large object interface, it is necessary to enclose it within a transaction block.
Note:
This function used to be called pg_loclose().
Returns TRUE on success or FALSE on failure.
Example #1 pg_lo_close() example
<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_create($database);
echo "$oid\n";
$handle = pg_lo_open($database, $oid, "w");
echo "$handle\n";
pg_lo_write($handle, "large object data");
pg_lo_close($handle);
pg_query($database, "commit");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_create — Create a large object
pg_lo_create() creates a large
object and returns the OID of the large
object. PostgreSQL access modes
INV_READ, INV_WRITE, and
INV_ARCHIVE are not supported, the
object is created always with both read and write
access. INV_ARCHIVE has been removed from PostgreSQL itself
(version 6.3 and above).
To use the large object interface, it is necessary to enclose it within a transaction block.
Instead of using the large object interface (which has no access controls and is cumbersome to use), try PostgreSQL's bytea column type and pg_escape_bytea().
Note:
This function used to be called pg_locreate().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
object_id
If an object_id is given the function
will try to create a large object with this id, else a free
object id is assigned by the server. The parameter
was added in PHP 5.3 and relies on functionality that first
appeared in PostgreSQL 8.1.
A large object OID or FALSE on error.
| Version | Description |
|---|---|
| 5.3.0 |
The optional |
Example #1 pg_lo_create() example
<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_create($database);
echo "$oid\n";
$handle = pg_lo_open($database, $oid, "w");
echo "$handle\n";
pg_lo_write($handle, "large object data");
pg_lo_close($handle);
pg_query($database, "commit");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_export — Export a large object to file
$connection
], int $oid
, string $pathname
) : boolpg_lo_export() takes a large object in a PostgreSQL database and saves its contents to a file on the local filesystem.
To use the large object interface, it is necessary to enclose it within a transaction block.
Note:
This function used to be called pg_loexport().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
oidThe OID of the large object in the database.
pathnameThe full path and file name of the file in which to write the large object on the client filesystem.
Returns TRUE on success or FALSE on failure.
Example #1 pg_lo_export() example
<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_create($database);
$handle = pg_lo_open($database, $oid, "w");
pg_lo_write($handle, "large object data");
pg_lo_close($handle);
pg_lo_export($database, $oid, '/tmp/lob.dat');
pg_query($database, "commit");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_import — Import a large object from file
pg_lo_import() creates a new large object in the database using a file on the filesystem as its data source.
To use the large object interface, it is necessary to enclose it within a transaction block.
Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
Note:
This function used to be called pg_loimport().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
pathnameThe full path and file name of the file on the client filesystem from which to read the large object data.
object_id
If an object_id is given the function
will try to create a large object with this id, else a free
object id is assigned by the server. The parameter
was added in PHP 5.3 and relies on functionality that first
appeared in PostgreSQL 8.1.
The OID of the newly created large object, or
FALSE on failure.
| Version | Description |
|---|---|
| 5.3.0 |
The optional |
Example #1 pg_lo_import() example
<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_import($database, '/tmp/lob.dat');
pg_query($database, "commit");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_open — Open a large object
$connection
, int $oid
, string $mode
) : resourcepg_lo_open() opens a large object in the database and returns large object resource so that it can be manipulated.
Do not close the database connection before closing the large object resource.
To use the large object interface, it is necessary to enclose it within a transaction block.
Note:
This function used to be called pg_loopen().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
oidThe OID of the large object in the database.
modeCan be either "r" for read-only, "w" for write only or "rw" for read and write.
A large object resource or FALSE on error.
Example #1 pg_lo_open() example
<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_create($database);
echo "$oid\n";
$handle = pg_lo_open($database, $oid, "w");
echo "$handle\n";
pg_lo_write($handle, "large object data");
pg_lo_close($handle);
pg_query($database, "commit");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_read_all — Reads an entire large object and send straight to browser
$large_object
) : intpg_lo_read_all() reads a large object and passes it straight through to the browser after sending all pending headers. Mainly intended for sending binary data like images or sound.
To use the large object interface, it is necessary to enclose it within a transaction block.
Note:
This function used to be called pg_loreadall().
Number of bytes read or FALSE on error.
Example #1 pg_lo_read_all() example
<?php
header('Content-type: image/jpeg');
$image_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $image_oid, "r");
pg_lo_read_all($handle);
pg_query($database, "commit");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_read — Read a large object
$large_object
[, int $len = 8192
] ) : string
pg_lo_read() reads at most
len bytes from a large object and
returns it as a string.
To use the large object interface, it is necessary to enclose it within a transaction block.
Note:
This function used to be called pg_loread().
large_objectPostgreSQL large object (LOB) resource, returned by pg_lo_open().
lenAn optional maximum number of bytes to return.
A string containing len bytes from the
large object, or FALSE on error.
Example #1 pg_lo_read() example
<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
$data = pg_lo_read($handle, 50000);
pg_query($database, "commit");
echo $data;
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_seek — Seeks position within a large object
$large_object
, int $offset
[, int $whence = PGSQL_SEEK_CUR
] ) : boolpg_lo_seek() seeks a position within a large object resource.
To use the large object interface, it is necessary to enclose it within a transaction block.
large_objectPostgreSQL large object (LOB) resource, returned by pg_lo_open().
offsetThe number of bytes to seek.
whence
One of the constants PGSQL_SEEK_SET (seek from object start),
PGSQL_SEEK_CUR (seek from current position)
or PGSQL_SEEK_END (seek from object end) .
Returns TRUE on success or FALSE on failure.
Example #1 pg_lo_seek() example
<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// Skip first 50000 bytes
pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
// Read the next 10000 bytes
$data = pg_lo_read($handle, 10000);
pg_query($database, "commit");
echo $data;
?>
| Version | Description |
|---|---|
| 5.6.0 | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object. |
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_tell — Returns current seek position a of large object
$large_object
) : intpg_lo_tell() returns the current position (offset from the beginning) of a large object.
To use the large object interface, it is necessary to enclose it within a transaction block.
The current seek offset (in number of bytes) from the beginning of the large object. If there is an error, the return value is negative.
Example #1 pg_lo_tell() example
<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// Skip first 50000 bytes
pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
// See how far we've skipped
$offset = pg_lo_tell($handle);
echo "Seek position is: $offset";
pg_query($database, "commit");
?>
The above example will output:
Seek position is: 50000
| Version | Description |
|---|---|
| 5.6.0 | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object. |
(PHP 5 >= 5.6.0, PHP 7)
pg_lo_truncate — Truncates a large object
$large_object
, int $size
) : boolpg_lo_truncate() truncates a large object resource.
To use the large object interface, it is necessary to enclose it within a transaction block.
large_objectPostgreSQL large object (LOB) resource, returned by pg_lo_open().
sizeThe number of bytes to truncate.
Returns TRUE on success or FALSE on failure.
Example #1 pg_lo_truncate() example
<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// Truncate to 0
pg_lo_truncate($handle, 0);
pg_query($database, "commit");
echo $data;
?>
| Version | Description |
|---|---|
| 5.6.0 | Added truncate function. It supports PostgreSQL 9.3's 64bit large object. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object. |
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_unlink — Delete a large object
$connection
, int $oid
) : bool
pg_lo_unlink() deletes a large object with the
oid. Returns TRUE on success or FALSE on failure.
To use the large object interface, it is necessary to enclose it within a transaction block.
Note:
This function used to be called pg_lounlink().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
oidThe OID of the large object in the database.
Returns TRUE on success or FALSE on failure.
Example #1 pg_lo_unlink() example
<?php
// OID of the large object to delete
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
pg_lo_unlink($database, $doc_oid);
pg_query($database, "commit");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_lo_write — Write to a large object
$large_object
, string $data
[, int $len
] ) : intpg_lo_write() writes data into a large object at the current seek position.
To use the large object interface, it is necessary to enclose it within a transaction block.
Note:
This function used to be called pg_lowrite().
large_objectPostgreSQL large object (LOB) resource, returned by pg_lo_open().
data
The data to be written to the large object. If len is
specified and is less than the length of data, only
len bytes will be written.
len
An optional maximum number of bytes to write. Must be greater than zero
and no greater than the length of data. Defaults to
the length of data.
The number of bytes written to the large object, or FALSE on error.
Example #1 pg_lo_write() example
<?php
$doc_oid = 189762345;
$data = "This will overwrite the start of the large object.";
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "w");
$data = pg_lo_write($handle, $data);
pg_query($database, "commit");
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_meta_data — Get meta data for table
$connection
, string $table_name
[, bool $extended = FALSE
] ) : array
pg_meta_data() returns table definition for
table_name as an array.
connectionPostgreSQL database connection resource.
table_nameThe name of the table.
extended
Flag for returning extended meta data. Default to FALSE.
An array of the table definition, or FALSE on error.
Example #1 Getting table metadata
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$meta = pg_meta_data($dbconn, 'authors');
if (is_array($meta)) {
echo '<pre>';
var_dump($meta);
echo '</pre>';
}
?>
The above example will output:
array(3) {
["author"]=>
array(5) {
["num"]=>
int(1)
["type"]=>
string(7) "varchar"
["len"]=>
int(-1)
["not null"]=>
bool(false)
["has default"]=>
bool(false)
}
["year"]=>
array(5) {
["num"]=>
int(2)
["type"]=>
string(4) "int2"
["len"]=>
int(2)
["not null"]=>
bool(false)
["has default"]=>
bool(false)
}
["title"]=>
array(5) {
["num"]=>
int(3)
["type"]=>
string(7) "varchar"
["len"]=>
int(-1)
["not null"]=>
bool(false)
["has default"]=>
bool(false)
}
}
| Version | Description |
|---|---|
| 5.6.0 |
No longer experimental. Added "is enum" as default attribute.
extended flag is added.
|
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_num_fields — Returns the number of fields in a result
$result
) : intpg_num_fields() returns the number of fields (columns) in a PostgreSQL result resource.
Note:
This function used to be called pg_numfields().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
The number of fields (columns) in the result. On error, -1 is returned.
Example #1 pg_num_fields() example
<?php
$result = pg_query($conn, "SELECT 1, 2");
$num = pg_num_fields($result);
echo $num . " field(s) returned.\n";
?>
The above example will output:
2 field(s) returned.
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_num_rows — Returns the number of rows in a result
$result
) : intpg_num_rows() will return the number of rows in a PostgreSQL result resource.
Note:
This function used to be called pg_numrows().
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
The number of rows in the result. On error, -1 is returned.
Example #1 pg_num_rows() example
<?php
$result = pg_query($conn, "SELECT 1");
$rows = pg_num_rows($result);
echo $rows . " row(s) returned.\n";
?>
The above example will output:
1 row(s) returned.
(PHP 4, PHP 5, PHP 7)
pg_options — Get the options associated with the connection
$connection
] ) : string
pg_options() will return a string containing
the options specified on the given PostgreSQL
connection resource.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
A string containing the connection
options, or FALSE on error.
Example #1 pg_options() example
<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
echo pg_options($pgsql_conn);
?>
(PHP 5, PHP 7)
pg_parameter_status — Looks up a current parameter setting of the server
$connection
], string $param_name
) : stringLooks up a current parameter setting of the server.
Certain parameter values are reported by the server automatically at
connection startup or whenever their values change. pg_parameter_status() can be
used to interrogate these settings. It returns the current value of a
parameter if known, or FALSE if the parameter is not known.
Parameters reported as of PostgreSQL 8.0 include server_version,
server_encoding, client_encoding,
is_superuser, session_authorization,
DateStyle, TimeZone, and integer_datetimes.
(server_encoding, TimeZone, and
integer_datetimes were not reported by releases before 8.0.) Note that
server_version, server_encoding and integer_datetimes
cannot change after PostgreSQL startup.
PostgreSQL 7.3 or lower servers do not report parameter settings,
pg_parameter_status()
includes logic to obtain values for server_version and
client_encoding
anyway. Applications are encouraged to use pg_parameter_status() rather than ad
hoc code to determine these values.
On a pre-7.4
PostgreSQL server, changing client_encoding via SET after connection startup will
not be reflected by pg_parameter_status().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
param_name
Possible param_name values include server_version,
server_encoding, client_encoding,
is_superuser, session_authorization,
DateStyle, TimeZone, and
integer_datetimes.
A string containing the value of the parameter, FALSE on failure or invalid
param_name.
Example #1 pg_parameter_status() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding");
?>
The above example will output:
Server encoding: SQL_ASCII
(PHP 4, PHP 5, PHP 7)
pg_pconnect — Open a persistent PostgreSQL connection
$connection_string
[, int $connect_type
] ) : resourcepg_pconnect() opens a connection to a PostgreSQL database. It returns a connection resource that is needed by other PostgreSQL functions.
If a second call is made to pg_pconnect() with
the same connection_string as an existing connection, the
existing connection will be returned unless you pass
PGSQL_CONNECT_FORCE_NEW as
connect_type.
To enable persistent connection, the pgsql.allow_persistent php.ini directive must be set to "On" (which is the default). The maximum number of persistent connection can be defined with the pgsql.max_persistent php.ini directive (defaults to -1 for no limit). The total number of connections can be set with the pgsql.max_links php.ini directive.
pg_close() will not close persistent links generated by pg_pconnect().
connection_string
The connection_string can be empty to use all default parameters, or it
can contain one or more parameter settings separated by whitespace.
Each parameter setting is in the form keyword = value. Spaces around
the equal sign are optional. To write an empty value or a value
containing spaces, surround it with single quotes, e.g., keyword =
'a value'. Single quotes and backslashes within the value must be
escaped with a backslash, i.e., \' and \\.
The currently recognized parameter keywords are:
host, hostaddr, port,
dbname, user,
password, connect_timeout,
options, tty (ignored), sslmode,
requiressl (deprecated in favor of sslmode), and
service. Which of these arguments exist depends
on your PostgreSQL version.
connect_type
If PGSQL_CONNECT_FORCE_NEW is passed, then a new connection
is created, even if the connection_string is identical to
an existing connection.
PostgreSQL connection resource on success, FALSE on failure.
Example #1 Using pg_pconnect()
<?php
$dbconn = pg_pconnect("dbname=mary");
//connect to a database named "mary"
$dbconn2 = pg_pconnect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"
$dbconn3 = pg_pconnect("host=sheep port=5432 dbname=mary user=lamb password=foo");
//connect to a database named "mary" on the host "sheep" with a username and password
$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_pconnect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_ping — Ping database connection
$connection
] ) : boolpg_ping() pings a database connection and tries to reconnect it if it is broken.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
Returns TRUE on success or FALSE on failure.
Example #1 pg_ping() example
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
if (!pg_ping($conn))
die("Connection is broken\n");
?>
(PHP 4, PHP 5, PHP 7)
pg_port — Return the port number associated with the connection
$connection
] ) : int
pg_port() returns the port number that the
given PostgreSQL connection resource is
connected to.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
An int containing the port number of the database
server the connection is to,
or FALSE on error.
Example #1 pg_port() example
<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
print "Successfully connected to port: " . pg_port($pgsql_conn) . "<br/>\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>
(PHP 5 >= 5.1.0, PHP 7)
pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion
$connection
], string $stmtname
, string $query
) : resourcepg_prepare() creates a prepared statement for later execution with pg_execute() or pg_send_execute(). This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. pg_prepare() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.
The function creates a prepared statement named stmtname from the query
string, which must contain a single SQL command. stmtname may be "" to
create an unnamed statement, in which case any pre-existing unnamed
statement is automatically replaced; otherwise it is an error if the
statement name is already defined in the current session. If any parameters
are used, they are referred to in the query as $1, $2, etc.
Prepared statements for use with pg_prepare() can also be created by
executing SQL PREPARE statements. (But pg_prepare() is more flexible since it
does not require parameter types to be pre-specified.) Also, although there
is no PHP function for deleting a prepared statement, the SQL DEALLOCATE
statement can be used for that purpose.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
stmtnameThe name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.
queryThe parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.
A query result resource on success or FALSE on failure.
Example #1 Using pg_prepare()
<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
?>
(PHP 4 >= 4.0.3, PHP 5, PHP 7)
pg_put_line — Send a NULL-terminated string to PostgreSQL backend
$connection
], string $data
) : bool
pg_put_line() sends a NULL-terminated string
to the PostgreSQL backend server. This is needed in conjunction
with PostgreSQL's COPY FROM command.
COPY is a high-speed data loading interface
supported by PostgreSQL. Data is passed in without being parsed,
and in a single transaction.
An alternative to using raw pg_put_line() commands is to use pg_copy_from(). This is a far simpler interface.
Note:
The application must explicitly send the two characters "\." on the last line to indicate to the backend that it has finished sending its data, before issuing pg_end_copy().
Use of the pg_put_line() causes most large object operations, including pg_lo_read() and pg_lo_tell(), to subsequently fail. You can use pg_copy_from() and pg_copy_to() instead.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
data
A line of text to be sent directly to the PostgreSQL backend. A NULL
terminator is added automatically.
Returns TRUE on success or FALSE on failure.
Example #1 pg_put_line() example
<?php
$conn = pg_pconnect("dbname=foo");
pg_query($conn, "create table bar (a int4, b char(16), d float8)");
pg_query($conn, "copy bar from stdin");
pg_put_line($conn, "3\thello world\t4.5\n");
pg_put_line($conn, "4\tgoodbye world\t7.11\n");
pg_put_line($conn, "\\.\n");
pg_end_copy($conn);
?>
(PHP 5 >= 5.1.0, PHP 7)
pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
$connection
], string $query
, array $params
) : resourceSubmits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.
If parameters are used, they are referred to in the
query string as $1, $2, etc. The same parameter may
appear more than once in the query; the same value
will be used in that case. params specifies the
actual values of the parameters. A NULL value in this array means the
corresponding parameter is SQL NULL.
The primary advantage of pg_query_params() over pg_query()
is that parameter values
may be separated from the query string, thus avoiding the need for tedious
and error-prone quoting and escaping. Unlike pg_query(),
pg_query_params() allows at
most one SQL command in the given string. (There can be semicolons in it,
but not more than one nonempty command.)
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
queryThe parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.
User-supplied values should always be passed as parameters, not interpolated into the query string, where they form possible SQL injection attack vectors and introduce bugs when handling data containing quotes. If for some reason you cannot use a parameter, ensure that interpolated values are properly escaped.
paramsAn array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.
Values intended for bytea fields are not supported as
parameters. Use pg_escape_bytea() instead, or use the
large object functions.
A query result resource on success or FALSE on failure.
Example #1 Using pg_query_params()
<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");
// Find all shops named Joe's Widgets. Note that it is not necessary to
// escape "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));
// Compare against just using pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_query — Execute a query
$connection
], string $query
) : resource
pg_query() executes the query
on the specified database connection.
pg_query_params() should be preferred
in most cases.
If an error occurs, and FALSE is returned, details of the error can
be retrieved using the pg_last_error()
function if the connection is valid.
Note: Although
connectioncan be omitted, it is not recommended, since it can be the cause of hard to find bugs in scripts.
Note:
This function used to be called pg_exec(). pg_exec() is still available for compatibility reasons, but users are encouraged to use the newer name.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
queryThe SQL statement or statements to be executed. When multiple statements are passed to the function, they are automatically executed as one transaction, unless there are explicit BEGIN/COMMIT commands included in the query string. However, using multiple transactions in one function call is not recommended.
String interpolation of user-supplied data is extremely dangerous and is likely to lead to SQL injection vulnerabilities. In most cases pg_query_params() should be preferred, passing user-supplied values as parameters rather than substituting them into the query string.
Any user-supplied data substituted directly into a query string should be properly escaped.
A query result resource on success or FALSE on failure.
Example #1 pg_query() example
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}
?>
Example #2 Using pg_query() with multiple statements
<?php
$conn = pg_pconnect("dbname=publisher");
// these statements will be executed as one transaction
$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
$query .= "UPDATE authors SET author=NULL WHERE id=3;";
pg_query($conn, $query);
?>
(PHP 5 >= 5.1.0, PHP 7)
pg_result_error_field — Returns an individual field of an error report
$result
, int $fieldcode
) : string
pg_result_error_field() returns one of the detailed error message
fields associated with result resource. It is only available
against a PostgreSQL 7.4 or above server. The error field is specified by
the fieldcode.
Because pg_query() and pg_query_params() return FALSE if the query fails,
you must use pg_send_query() and
pg_get_result() to get the result handle.
If you need to get additional error information from failed pg_query() queries, use pg_set_error_verbosity() and pg_last_error() and then parse the result.
resultA PostgreSQL query result resource from a previously executed statement.
fieldcode
Possible fieldcode values are: PGSQL_DIAG_SEVERITY,
PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY,
PGSQL_DIAG_MESSAGE_DETAIL,
PGSQL_DIAG_MESSAGE_HINT, PGSQL_DIAG_STATEMENT_POSITION,
PGSQL_DIAG_INTERNAL_POSITION (PostgreSQL 8.0+ only),
PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+ only),
PGSQL_DIAG_CONTEXT, PGSQL_DIAG_SOURCE_FILE,
PGSQL_DIAG_SOURCE_LINE or
PGSQL_DIAG_SOURCE_FUNCTION.
A string containing the contents of the error field, NULL if the field does not exist or FALSE
on failure.
Example #1 pg_result_error_field() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}
$res1 = pg_get_result($dbconn);
echo pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE);
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_result_error — Get error message associated with result
$result
) : string
pg_result_error() returns any error message
associated with the result resource. Therefore,
the user has a better chance of getting the correct error message than
with pg_last_error().
The function pg_result_error_field() can give much greater detail on result errors than pg_result_error().
Because pg_query() returns FALSE if the query fails,
you must use pg_send_query() and
pg_get_result() to get the result handle.
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
Returns a string. Returns empty string if there is no error. If there is an error associated with the
result parameter, returns FALSE.
Example #1 pg_result_error() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}
$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_result_seek — Set internal row offset in result resource
$result
, int $offset
) : boolpg_result_seek() sets the internal row offset in a result resource.
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
offset
Row to move the internal offset to in the result resource.
Rows are numbered starting from zero.
Returns TRUE on success or FALSE on failure.
Example #1 pg_result_seek() example
<?php
// Connect to the database
$conn = pg_pconnect("dbname=publisher");
// Execute a query
$result = pg_query($conn, "SELECT author, email FROM authors");
// Seek to the 3rd row (assuming there are 3 rows)
pg_result_seek($result, 2);
// Fetch the 3rd row
$row = pg_fetch_row($result);
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_result_status — Get status of query result
pg_result_status() returns the status of a result resource, or the PostgreSQL command completion tag associated with the result
resultPostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
type
Either PGSQL_STATUS_LONG to return the numeric status
of the result, or PGSQL_STATUS_STRING
to return the command tag of the result.
If not specified, PGSQL_STATUS_LONG is the default.
Possible return values are PGSQL_EMPTY_QUERY,
PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_OUT,
PGSQL_COPY_IN, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR and
PGSQL_FATAL_ERROR if PGSQL_STATUS_LONG is
specified. Otherwise, a string containing the PostgreSQL command tag is returned.
Example #1 pg_result_status() example
<?php
// Connect to the database
$conn = pg_pconnect("dbname=publisher");
// Execute a COPY
$result = pg_query($conn, "COPY authors FROM STDIN;");
// Get the result status
$status = pg_result_status($result);
// Determine status
if ($status == PGSQL_COPY_IN)
echo "Copy began.";
else
echo "Copy failed.";
?>
The above example will output:
Copy began.
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_select — Select records
$connection
, string $table_name
, array $assoc_array
[, int $options = PGSQL_DML_EXEC
[, int $result_type = PGSQL_ASSOC
]] ) : mixed
pg_select() selects records specified by
assoc_array which has
field=>value. For a successful query, it returns an
array containing all records and fields that match the condition
specified by assoc_array.
If options is specified,
pg_convert() is applied to
assoc_array with the specified flags.
By default pg_select() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes parameters/identifiers. Therefore, table/column names became case sensitive.
Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.
connectionPostgreSQL database connection resource.
table_nameName of the table from which to select rows.
assoc_array
An array whose keys are field names in the table table_name,
and whose values are the conditions that a row must meet to be retrieved.
options
Any number of PGSQL_CONV_FORCE_NULL,
PGSQL_DML_NO_CONV,
PGSQL_DML_ESCAPE,
PGSQL_DML_EXEC,
PGSQL_DML_ASYNC or
PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the
options then query string is returned. When PGSQL_DML_NO_CONV
or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.
Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed
via options.
Example #1 pg_select() example
<?php
$db = pg_connect('dbname=foo');
// This is safe somewhat, since all values are escaped.
// However PostgreSQL supports JSON/Array. These are not
// safe by neither escape nor prepared query.
$rec = pg_select($db, 'post_log', $_POST, PG_DML_ESCAPE);
if ($rec) {
echo "Records selected\n";
var_dump($rec);
} else {
echo "User must have sent wrong inputs\n";
}
?>
| Version | Description |
|---|---|
| 7.1.0 |
The result_type parameter was added.
|
| 5.6.0 |
No longer experimental. Added PGSQL_DML_ESCAPE constant,
TRUE/FALSE and NULL data type support.
|
| 5.5.3/5.4.19 |
Direct SQL injection to table_name and Indirect SQL
injection to identifiers are fixed.
|
(PHP 5 >= 5.1.0, PHP 7)
pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
$connection
, string $stmtname
, array $params
) : boolSends a request to execute a prepared statement with given parameters, without waiting for the result(s).
This is similar to pg_send_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of PostgreSQL.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
stmtname
The name of the prepared statement to execute. if
"" is specified, then the unnamed statement is executed. The name must have
been previously prepared using pg_prepare(),
pg_send_prepare() or a PREPARE SQL
command.
paramsAn array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.
Returns TRUE on success, FALSE on failure. Use pg_get_result()
to determine the query result.
Example #1 Using pg_send_execute()
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Prepare a query for execution
if (!pg_connection_busy($dbconn)) {
pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
$res1 = pg_get_result($dbconn);
}
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
$res2 = pg_get_result($dbconn);
}
// Execute the same prepared query, this time with a different parameter
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
$res3 = pg_get_result($dbconn);
}
?>
(PHP 5 >= 5.1.0, PHP 7)
pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion
$connection
, string $stmtname
, string $query
) : boolSends a request to create a prepared statement with the given parameters, without waiting for completion.
This is an asynchronous version of pg_prepare(): it returns TRUE if it was able to
dispatch the request, and FALSE if not. After a successful call, call
pg_get_result() to determine whether the server successfully created the
prepared statement. The function's parameters are handled identically to
pg_prepare(). Like pg_prepare(), it will not work
on pre-7.4 versions of PostgreSQL.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
stmtnameThe name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.
queryThe parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.
Returns TRUE on success, FALSE on failure. Use pg_get_result()
to determine the query result.
Example #1 Using pg_send_prepare()
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Prepare a query for execution
if (!pg_connection_busy($dbconn)) {
pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
$res1 = pg_get_result($dbconn);
}
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
$res2 = pg_get_result($dbconn);
}
// Execute the same prepared query, this time with a different parameter
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
$res3 = pg_get_result($dbconn);
}
?>
(PHP 5 >= 5.1.0, PHP 7)
pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s)
$connection
, string $query
, array $params
) : boolSubmits a command and separate parameters to the server without waiting for the result(s).
This is equivalent to pg_send_query() except that query
parameters can be specified separately from the
query string. The function's parameters are
handled identically to pg_query_params(). Like
pg_query_params(), it will not work on pre-7.4 PostgreSQL
connections, and it allows only one command in the query string.
connectionPostgreSQL database connection resource.
queryThe parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.
paramsAn array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.
Returns TRUE on success or FALSE on failure.
Use pg_get_result() to determine the query result.
Example #1 Using pg_send_query_params()
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
// Using parameters. Note that it is not necessary to quote or escape
// the parameter.
pg_send_query_params($dbconn, 'select count(*) from authors where city = $1', array('Perth'));
// Compare against basic pg_send_query usage
$str = pg_escape_string('Perth');
pg_send_query($dbconn, "select count(*) from authors where city = '${str}'");
?>
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
pg_send_query — Sends asynchronous query
$connection
, string $query
) : bool
pg_send_query() sends a query or queries asynchronously to the
connection. Unlike
pg_query(), it can send multiple queries at once to
PostgreSQL and get the results one by one using
pg_get_result().
Script execution is not blocked while the queries are executing. Use pg_connection_busy() to check if the connection is busy (i.e. the query is executing). Queries may be cancelled using pg_cancel_query().
Although the user can send multiple queries at once, multiple queries cannot be sent over a busy connection. If a query is sent while the connection is busy, it waits until the last query is finished and discards all its results.
connectionPostgreSQL database connection resource.
queryThe SQL statement or statements to be executed.
Data inside the query should be properly escaped.
Returns TRUE on success or FALSE on failure.
Use pg_get_result() to determine the query result.
Example #1 pg_send_query() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}
$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo "$res1 has $rows1 records\n\n";
$res2 = pg_get_result($dbconn);
echo "Second call to pg_get_result(): $res2\n";
$rows2 = pg_num_rows($res2);
echo "$res2 has $rows2 records\n";
?>
The above example will output:
First call to pg_get_result(): Resource id #3 Resource id #3 has 3 records Second call to pg_get_result(): Resource id #4 Resource id #4 has 1 records
(PHP 4 >= 4.0.3, PHP 5, PHP 7)
pg_set_client_encoding — Set the client encoding
$connection
], string $encoding
) : intpg_set_client_encoding() sets the client encoding and returns 0 if success or -1 if error.
PostgreSQL will automatically convert data in the backend database encoding into the frontend encoding.
Note:
The function used to be called pg_setclientencoding().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
encoding
The required client encoding. One of SQL_ASCII, EUC_JP,
EUC_CN, EUC_KR, EUC_TW,
UNICODE, MULE_INTERNAL, LATINX (X=1...9),
KOI8, WIN, ALT, SJIS,
BIG5 or WIN1250.
The exact list of available encodings depends on your PostgreSQL version, so check your PostgreSQL manual for a more specific list.
Returns 0 on success or -1 on error.
Example #1 pg_set_client_encoding() example
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
// Set the client encoding to UNICODE. Data will be automatically
// converted from the backend encoding to the frontend.
pg_set_client_encoding($conn, "UNICODE");
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
// Write out UTF-8 data
while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}
?>
(PHP 5 >= 5.1.0, PHP 7)
pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error() and pg_result_error()
$connection
], int $verbosity
) : intDetermines the verbosity of messages returned by pg_last_error() and pg_result_error().
pg_set_error_verbosity() sets the verbosity mode, returning the connection's previous
setting. In PGSQL_ERRORS_TERSE mode, returned messages include severity, primary text, and
position only; this will normally fit on a single line. The default mode (PGSQL_ERRORS_DEFAULT)
produces messages that include the above plus any detail, hint, or context
fields (these may span multiple lines). The PGSQL_ERRORS_VERBOSE mode includes all available
fields. Changing the verbosity does not affect the messages available from
already-existing result objects, only subsequently-created ones.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
verbosity
The required verbosity: PGSQL_ERRORS_TERSE,
PGSQL_ERRORS_DEFAULT
or PGSQL_ERRORS_VERBOSE.
The previous verbosity level: PGSQL_ERRORS_TERSE,
PGSQL_ERRORS_DEFAULT
or PGSQL_ERRORS_VERBOSE.
Example #1 pg_set_error_verbosity() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}
pg_set_error_verbosity($dbconn, PGSQL_ERRORS_VERBOSE);
$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>
(PHP 5 >= 5.6.0, PHP 7)
pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection
$connection
) : resourcepg_socket() returns a read only resource corresponding to the socket underlying the given PostgreSQL connection.
This function is currently not documented; only its argument list is available.
connectionPostgreSQL database connection resource.
A socket resource on success or FALSE on failure.
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
pg_trace — Enable tracing a PostgreSQL connection
$pathname
[, string $mode = "w"
[, resource $connection
]] ) : boolpg_trace() enables tracing of the PostgreSQL frontend/backend communication to a file. To fully understand the results, one needs to be familiar with the internals of PostgreSQL communication protocol.
For those who are not, it can still be useful for tracing errors in queries sent to the server, you could do for example grep '^To backend' trace.log and see what queries actually were sent to the PostgreSQL server. For more information, refer to the » PostgreSQL Documentation.
pathnameThe full path and file name of the file in which to write the trace log. Same as in fopen().
modeAn optional file access mode, same as for fopen().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
Returns TRUE on success or FALSE on failure.
Example #1 pg_trace() example
<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
pg_query("SELECT 1");
pg_untrace($pgsql_conn);
// Now /tmp/trace.log will contain backend communication
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>
(PHP 5 >= 5.1.0, PHP 7)
pg_transaction_status — Returns the current in-transaction status of the server
$connection
) : intReturns the current in-transaction status of the server.
pg_transaction_status() will give incorrect results when using
a PostgreSQL 7.3 server that has the parameter autocommit
set to off. The server-side autocommit feature has been
deprecated and does not exist in later server versions.
connectionPostgreSQL database connection resource.
The status can be PGSQL_TRANSACTION_IDLE (currently idle),
PGSQL_TRANSACTION_ACTIVE (a command is in progress),
PGSQL_TRANSACTION_INTRANS (idle, in a valid transaction block),
or PGSQL_TRANSACTION_INERROR (idle, in a failed transaction block).
PGSQL_TRANSACTION_UNKNOWN is reported if the connection is bad.
PGSQL_TRANSACTION_ACTIVE is reported only when a query
has been sent to the server and not yet completed.
Example #1 pg_transaction_status() example
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$stat = pg_transaction_status($dbconn);
if ($stat === PGSQL_TRANSACTION_UNKNOWN) {
echo 'Connection is bad';
} else if ($stat === PGSQL_TRANSACTION_IDLE) {
echo 'Connection is currently idle';
} else {
echo 'Connection is in a transaction state';
}
?>
(PHP 4, PHP 5, PHP 7)
pg_tty — Return the TTY name associated with the connection
$connection
] ) : string
pg_tty() returns the TTY name that server
side debugging output is sent to on the given PostgreSQL
connection resource.
Note:
pg_tty() is obsolete, since the server no longer pays attention to the TTY setting, but the function remains for backwards compatibility.
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
A string containing the debug TTY of
the connection, or FALSE on error.
Example #1 pg_tty() example
<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
print "Server debug TTY is: " . pg_tty($pgsql_conn) . "<br/>\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_unescape_bytea — Unescape binary for bytea type
$data
) : stringpg_unescape_bytea() unescapes PostgreSQL bytea data values. It returns the unescaped string, possibly containing binary data.
Note:
When you
SELECTa bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e.
INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea);PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.
A string containing the unescaped data.
Example #1 pg_unescape_bytea() example
<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');
// Get the bytea data
$res = pg_query("SELECT data FROM gallery WHERE name='Pine trees'");
$raw = pg_fetch_result($res, 'data');
// Convert to binary and send to the browser
header('Content-type: image/jpeg');
echo pg_unescape_bytea($raw);
?>
| Version | Description |
|---|---|
| 5.5.1 | A warning is thrown if the input string is invalid. |
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
pg_untrace — Disable tracing of a PostgreSQL connection
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
Always returns TRUE.
Example #1 pg_untrace() example
<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
if ($pgsql_conn) {
pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
pg_query("SELECT 1");
pg_untrace($pgsql_conn);
// Now tracing of backend communication is disabled
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
pg_update — Update table
$connection
, string $table_name
, array $data
, array $condition
[, int $options = PGSQL_DML_EXEC
] ) : mixed
pg_update() updates records that matches
condition with data. If
options is specified,
pg_convert() is applied to
data with specified options.
pg_update() updates records specified by
assoc_array which has
field=>value.
If options is specified,
pg_convert() is applied to
assoc_array with the specified flags.
By default pg_update() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes parameters/identifiers. Therefore, table/column names became case sensitive.
Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.
connectionPostgreSQL database connection resource.
table_nameName of the table into which to update rows.
data
An array whose keys are field names in the table table_name,
and whose values are what matched rows are to be updated to.
condition
An array whose keys are field names in the table table_name,
and whose values are the conditions that a row must meet to be updated.
options
Any number of PGSQL_CONV_FORCE_NULL,
PGSQL_DML_NO_CONV,
PGSQL_DML_ESCAPE,
PGSQL_DML_EXEC,
PGSQL_DML_ASYNC or
PGSQL_DML_STRING combined. If PGSQL_DML_STRING is part of the
options then query string is returned. When PGSQL_DML_NO_CONV
or PGSQL_DML_ESCAPE is set, it does not call pg_convert() internally.
Returns TRUE on success or FALSE on failure. Returns string if PGSQL_DML_STRING is passed
via options.
Example #1 pg_update() example
<?php
$db = pg_connect('dbname=foo');
$data = array('field1'=>'AA', 'field2'=>'BB');
// This is safe somewhat, since all values are escaped.
// However PostgreSQL supports JSON/Array. These are not
// safe by neither escape nor prepared query.
$res = pg_update($db, 'post_log', $_POST, $data);
if ($res) {
echo "Data is updated: $res\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>
| Version | Description |
|---|---|
| 5.6.0 |
No longer experimental. Added PGSQL_DML_ESCAPE constant,
TRUE/FALSE and NULL data type support.
|
| 5.5.3/5.4.19 |
Direct SQL injection to table_name and Indirect
SQL injection to identifiers are fixed.
|
(PHP 5, PHP 7)
pg_version — Returns an array with client, protocol and server version (when available)
$connection
] ) : arraypg_version() returns an array with the client, protocol and server version. Protocol and server versions are only available if PHP was compiled with PostgreSQL 7.4 or later.
For more detailed server information, use pg_parameter_status().
connection
PostgreSQL database connection resource. When
connection is not present, the default connection
is used. The default connection is the last connection made by
pg_connect() or pg_pconnect().
Returns an array with client, protocol
and server keys and values (if available). Returns
FALSE on error or invalid connection.
Example #1 pg_version() example
<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
or die("Could not connect");
$v = pg_version($dbconn);
echo $v['client'];
?>
The above example will output:
7.4
This is an extension for the SQLite Embeddable SQL Database Engine. SQLite is a C library that implements an embeddable SQL database engine. Programs that link with the SQLite library can have SQL database access without running a separate RDBMS process.
SQLite is not a client library used to connect to a big database server. SQLite is the server. The SQLite library reads and writes directly to and from the database files on disk.
Note:
For further information see the SQLite Website (» http://sqlite.org/).
Note: This extension offers support for SQLite 2.x. Sqlite 3.x is supported by the SQLite3 extension.
The SQLite extension is enabled by default as of PHP 5.0. Beginning with PHP 5.4, the SQLite extension is available only via PECL.
Since PHP 5.0 this extension was bundled with PHP. Beginning with PHP 5.4, this extension is available only via PECL.
Windows users must enable php_sqlite.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
Windows builds must also enable PDO because as of PHP 5.1.0 it depends on it. So, php.ini will end up with something like this:
extension=php_pdo.dll extension=php_sqlite.dll
The PHP 5.0.x series of Windows builds enabled this extension by default, where no DLL file is necessary.
SQLite 3 is supported through PDO SQLite.
Note: Windows installation for unprivileged accounts
On Windows operating systems, unprivileged accounts don't have the TMP environment variable set by default. This will make sqlite create temporary files in the windows directory, which is not desirable. So, you should set the TMP environment variable for the web server or the user account the web server is running under. If Apache is your web server, you can accomplish this via a SetEnv directive in your httpd.conf file. For example:
If you are unable to establish this setting at the server level, you can implement the setting in your script:SetEnv TMP c:/tempThe setting must refer to a directory that the web server has permission to create files in and subsequently write to and delete the files it created. Otherwise, you may receive the following error message: malformed database schema - unable to open a temporary database file for storing temporary tables<?php
putenv('TMP=C:/temp');
?>
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| sqlite.assoc_case | "0" | PHP_INI_ALL | Available since PHP 5.0.0. |
Here's a short explanation of the configuration directives.
sqlite.assoc_case
int
Whether to use mixed case (0), upper case
(1) or lower case (2) hash
indexes.
This option is primarily useful when you need compatibility with other database systems, where the names of the columns are always returned as uppercase or lowercase, regardless of the case of the actual field names in the database schema.
The SQLite library returns the column names in their natural case (that
matches the case you used in your schema). When
sqlite.assoc_case is set to 0
the natural case will be preserved. When it is set to
1 or 2, PHP will apply case
folding on the hash keys to upper- or lower-case the keys, respectively.
Use of this option incurs a slight performance penalty, but is MUCH faster than performing the case folding yourself using PHP script.
There are two resources used in the SQLite Interface. The first one is the database connection, the second one the result set.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
The functions sqlite_fetch_array() and sqlite_current() use a constant for the different types of result arrays. The following constants are defined:
SQLITE_ASSOC
(int)
SQLITE_BOTH
(int)
SQLITE_NUM
(int)
A number of functions may return status codes. The following constants are defined:
SQLITE_OK
(int)
SQLITE_ERROR
(int)
SQLITE_INTERNAL
(int)
SQLITE_PERM
(int)
SQLITE_ABORT
(int)
SQLITE_BUSY
(int)
SQLITE_LOCKED
(int)
SQLITE_NOMEM
(int)
SQLITE_READONLY
(int)
SQLITE_INTERRUPT
(int)
SQLITE_IOERR
(int)
SQLITE_NOTADB
(int)
SQLITE_CORRUPT
(int)
SQLITE_FORMAT
(int)
SQLITE_NOTFOUND
(int)
SQLITE_FULL
(int)
SQLITE_CANTOPEN
(int)
SQLITE_PROTOCOL
(int)
SQLITE_EMPTY
(int)
SQLITE_SCHEMA
(int)
SQLITE_TOOBIG
(int)
SQLITE_CONSTRAINT
(int)
SQLITE_MISMATCH
(int)
SQLITE_MISUSE
(int)
SQLITE_NOLFS
(int)
SQLITE_AUTH
(int)
SQLITE_ROW
(int)
SQLITE_DONE
(int)
Represents an opened SQLite database.
Represents a buffered SQLite result set.
Represents an unbuffered SQLite result set. Unbuffered results sets are sequential, forward-seeking only.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_array_query -- SQLiteDatabase::arrayQuery — Execute a query against a given database and returns an array
$dbhandle
, string $query
[, int $result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : array$query
, resource $dbhandle
[, int $result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : arrayObject oriented style (method):
$query
[, int $result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : arraysqlite_array_query() executes the given query and returns an array of the entire result set. It is similar to calling sqlite_query() and then sqlite_fetch_array() for each row in the result set. sqlite_array_query() is significantly faster than the aforementioned.
sqlite_array_query() is best suited to queries returning 45 rows or less. If you have more data than that, it is recommended that you write your scripts to use sqlite_unbuffered_query() instead for more optimal performance.
queryThe query to be executed.
Data inside the query should be properly escaped.
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
result_typeThe optional result_type
parameter accepts a constant and determines how the returned array will be
indexed. Using SQLITE_ASSOC will return only associative
indices (named fields) while SQLITE_NUM will return
only numerical indices (ordinal field numbers). SQLITE_BOTH
will return both associative and numerical indices.
SQLITE_BOTH is the default for this function.
decode_binaryWhen the decode_binary
parameter is set to TRUE (the default), PHP will decode the binary encoding
it applied to the data if it was encoded using the
sqlite_escape_string(). You should normally leave this
value at its default, unless you are interoperating with databases created by
other sqlite capable applications.
Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the
dbhandleparameter is the first parameter to the function.
Returns an array of the entire result set; FALSE otherwise.
The column names returned by
SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the
sqlite.assoc_case configuration
option.
Example #1 Procedural style
<?php
$dbhandle = sqlite_open('sqlitedb');
$result = sqlite_array_query($dbhandle, 'SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
echo 'Name: ' . $entry['name'] . ' E-mail: ' . $entry['email'];
}
?>
Example #2 Object-oriented style
<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$result = $dbhandle->arrayQuery('SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
echo 'Name: ' . $entry['name'] . ' E-mail: ' . $entry['email'];
}
?>
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_busy_timeout -- SQLiteDatabase::busyTimeout — Set busy timeout duration, or disable busy handlers
$dbhandle
, int $milliseconds
) : voidObject oriented style (method):
$milliseconds
) : void
Set the maximum time, in milliseconds, that SQLite will wait for a
dbhandle to become ready for use.
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
milliseconds
The number of milliseconds. When set to
0, busy handlers will be disabled and SQLite will
return immediately with a SQLITE_BUSY status code
if another process/thread has the database locked for an update.
PHP sets the default busy timeout to be 60 seconds when the database is opened.
Note:
There are one thousand (1000) milliseconds in one second.
No value is returned.
Example #1 Procedural style
<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_busy_timeout($dbhandle, 10000); // set timeout to 10 seconds
sqlite_busy_timeout($dbhandle, 0); // disable busy handler
?>
Example #2 Object oriented style
<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->busyTimeout(10000); // 10 seconds
$dbhandle->busyTimeout(0); // disable
?>
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_changes -- SQLiteDatabase::changes — Returns the number of rows that were changed by the most recent SQL statement
$dbhandle
) : intObject oriented style (method):
Returns the numbers of rows that were changed by the most recent SQL
statement executed against the dbhandle database
handle.
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
Returns the number of changed rows.
Example #1 Procedural style
<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_query($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
exit('Error in query.');
} else {
echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>
Example #2 Object oriented style
<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->query("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
exit('Error in query.');
} else {
echo 'Number of rows modified: ', $dbhandle->changes();
}
?>
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_close — Closes an open SQLite database
$dbhandle
) : void
Closes the given db_handle database handle.
If the database was persistent, it will be closed and removed from the
persistent list.
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally.
No value is returned.
Example #1 sqlite_close() example
<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_close($dbhandle);
?>
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_column -- SQLiteResult::column -- SQLiteUnbuffered::column — Fetches a column from the current row of a result set
Fetches the value of a column named index_or_name
(if it is a string), or of the ordinal column numbered
index_or_name (if it is an integer) from the
current row of the query result handle result.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
index_or_nameThe column index or name to fetch.
decode_binaryWhen the decode_binary
parameter is set to TRUE (the default), PHP will decode the binary encoding
it applied to the data if it was encoded using the
sqlite_escape_string(). You should normally leave this
value at its default, unless you are interoperating with databases created by
other sqlite capable applications.
Returns the column value.
Note:
Use this function when you are iterating a large result set with many columns, or with columns that contain large amounts of data.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_create_aggregate -- SQLiteDatabase::createAggregate — Register an aggregating UDF for use in SQL statements
$dbhandle
, string $function_name
, callable $step_func
, callable $finalize_func
[, int $num_args = -1
] ) : voidObject oriented style (method):
$function_name
, callable $step_func
, callable $finalize_func
[, int $num_args = -1
] ) : voidsqlite_create_aggregate() is similar to sqlite_create_function() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.
The key difference between this function and
sqlite_create_function() is that two functions are
required to manage the aggregate; step_func is
called for each row of the result set. Your PHP function should
accumulate the result and store it into the aggregation context.
Once all the rows have been processed,
finalize_func will be called and it should then
take the data from the aggregation context and return the result.
Callback functions should return a type understood by SQLite (i.e.
scalar type).
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
function_nameThe name of the function used in SQL statements.
step_func
Callback function called for each row of the result set.
Function parameters are &$context, $value, ....
finalize_func
Callback function to aggregate the "stepped" data from each row.
Function parameter is &$context and the function
should return the final result of aggregation.
num_argsHint to the SQLite parser if the callback function accepts a predetermined number of arguments.
No value is returned.
Example #1 max_length aggregation function example
<?php
$data = array(
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
);
$dbhandle = sqlite_open(':memory:');
sqlite_query($dbhandle, "CREATE TABLE strings(a)");
foreach ($data as $str) {
$str = sqlite_escape_string($str);
sqlite_query($dbhandle, "INSERT INTO strings VALUES ('$str')");
}
function max_len_step(&$context, $string)
{
if (strlen($string) > $context) {
$context = strlen($string);
}
}
function max_len_finalize(&$context)
{
return $context;
}
sqlite_create_aggregate($dbhandle, 'max_len', 'max_len_step', 'max_len_finalize');
var_dump(sqlite_array_query($dbhandle, 'SELECT max_len(a) from strings'));
?>
In this example, we are creating an aggregating function that will
calculate the length of the longest string in one of the columns of the
table. For each row, the max_len_step function is
called and passed a context parameter. The context
parameter is just like any other PHP variable and be set to hold an array
or even an object value. In this example, we are simply using it to hold
the maximum length we have seen so far; if the
string has a length longer than the current
maximum, we update the context to hold this new maximum length.
After all of the rows have been processed, SQLite calls the
max_len_finalize function to determine the aggregate
result. Here, we could perform some kind of calculation based on the
data found in the context. In our simple example
though, we have been calculating the result as the query progressed, so we
simply need to return the context value.
Note:
The example above will not work correctly if the column contains binary data. Take a look at the manual page for sqlite_udf_decode_binary() for an explanation of why this is so, and an example of how to make it respect the binary encoding.
It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.
You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.
(PHP 5 < 5.4.0, sqlite >= 1.0.0)
sqlite_create_function -- SQLiteDatabase::createFunction — Registers a "regular" User Defined Function for use in SQL statements
$dbhandle
, string $function_name
, callable $callback
[, int $num_args = -1
] ) : voidObject oriented style (method):
$function_name
, callable $callback
[, int $num_args = -1
] ) : voidsqlite_create_function() allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.
The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
function_nameThe name of the function used in SQL statements.
callbackCallback function to handle the defined SQL function.
Note: Callback functions should return a type understood by SQLite (i.e. scalar type).
num_argsHint to the SQLite parser if the callback function accepts a predetermined number of arguments.
Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the
dbhandleparameter is the first parameter to the function.
No value is returned.
Example #1 sqlite_create_function() example
<?php
function md5_and_reverse($string)
{
return strrev(md5($string));
}
if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {
sqlite_create_function($dbhandle, 'md5rev', 'md5_and_reverse', 1);
$sql = 'SELECT md5rev(filename) FROM files';
$rows = sqlite_array_query($dbhandle, $sql);
} else {
echo 'Error opening sqlite db: ' . $sqliteerror;
exit;
}
?>
In this example, we have a function that calculates the md5 sum of a
string, and then reverses it. When the SQL statement executes, it
returns the value of the filename transformed by our function. The data
returned in $rows contains the processed result.
The beauty of this technique is that you do not need to process the result using a foreach loop after you have queried for the data.
PHP registers a special function named php when the
database is first opened. The php function can be used to call any PHP
function without having to register it first.
Example #2 Example of using the PHP function
<?php
$rows = sqlite_array_query($dbhandle, "SELECT php('md5', filename) from files");
?>
This example will call the md5() on each
filename column in the database and return the result
into $rows
Note:
For performance reasons, PHP will not automatically encode/decode binary data passed to and from your UDF's. You need to manually encode/decode the parameters and return values if you need to process binary data in this way. Take a look at sqlite_udf_encode_binary() and sqlite_udf_decode_binary() for more details.
It is not recommended to use UDF's to handle processing of binary data, unless high performance is not a key requirement of your application.
You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_current -- SQLiteResult::current -- SQLiteUnbuffered::current — Fetches the current row from a result set as an array
$result
[, int $result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : arrayObject oriented style (method):
$result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : array$result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : arraysqlite_current() is identical to sqlite_fetch_array() except that it does not advance to the next row prior to returning the data; it returns the data from the current position only.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
result_typeThe optional result_type
parameter accepts a constant and determines how the returned array will be
indexed. Using SQLITE_ASSOC will return only associative
indices (named fields) while SQLITE_NUM will return
only numerical indices (ordinal field numbers). SQLITE_BOTH
will return both associative and numerical indices.
SQLITE_BOTH is the default for this function.
decode_binaryWhen the decode_binary
parameter is set to TRUE (the default), PHP will decode the binary encoding
it applied to the data if it was encoded using the
sqlite_escape_string(). You should normally leave this
value at its default, unless you are interoperating with databases created by
other sqlite capable applications.
Returns an array of the current row from a result set; FALSE if the
current position is beyond the final row.
The column names returned by
SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the
sqlite.assoc_case configuration
option.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_error_string — Returns the textual description of an error code
$error_code
) : string
Returns a human readable description of the
error_code returned from
sqlite_last_error().
Returns a human readable description of the error_code,
as a string.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_escape_string — Escapes a string for use as a query parameter
$item
) : string
sqlite_escape_string() will correctly quote the string
specified by item
for use in an SQLite SQL statement. This includes doubling up
single-quote characters (') and checking for
binary-unsafe characters in the query string.
Although the encoding makes it safe to insert the data, it will render
simple text comparisons and LIKE clauses in your
queries unusable for the columns that contain the binary data. In
practice, this shouldn't be a problem, as your schema should be such that
you don't use such things on binary columns (in fact, it might be better to
store binary data using other means, such as in files).
itemThe string being quoted.
If the item contains a NUL
character, or if it begins with a character whose ordinal value is
0x01, PHP will apply a binary encoding scheme so that
you can safely store and retrieve binary data.
Returns an escaped string for use in an SQLite SQL statement.
Note: Do not use this function to encode the return values from UDF's created using sqlite_create_function() or sqlite_create_aggregate() - use sqlite_udf_encode_binary() instead.
addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.3)
sqlite_exec -- SQLiteDatabase::exec — Executes a result-less query against a given database
$dbhandle
, string $query
[, string &$error_msg
] ) : bool$query
, resource $dbhandle
) : boolObject oriented style (method):
$query
[, string &$error_msg
] ) : bool
Executes an SQL statement given by the query against
a given database handle (specified by the dbhandle
parameter).
SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script.
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
queryThe query to be executed.
Data inside the query should be properly escaped.
error_msgThe specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.
Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the
dbhandleparameter is the first parameter to the function.
This function will return a boolean result; TRUE for success or FALSE for failure.
If you need to run a query that returns rows, see sqlite_query().
The column names returned by
SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the
sqlite.assoc_case configuration
option.
| Version | Description |
|---|---|
| 5.1.0 |
Added the error_msg parameter
|
Example #1 Procedural example
<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_exec($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
exit("Error in query: '$error'");
} else {
echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>
Example #2 Object-oriented example
<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->queryExec("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
exit("Error in query: '$error'");
} else {
echo 'Number of rows modified: ', $dbhandle->changes();
}
?>
(PHP 5 < 5.4.0)
sqlite_factory — Opens an SQLite database and returns an SQLiteDatabase object
$filename
[, int $mode = 0666
[, string &$error_message
]] ) : SQLiteDatabasesqlite_factory() behaves similarly to sqlite_open() in that it opens an SQLite database or attempts to create it if it does not exist. However, a SQLiteDatabase object is returned rather than a resource. Please see the sqlite_open() reference page for further usage and caveats.
filenameThe filename of the SQLite database.
mode
The mode of the file. Intended to be used to open the database in
read-only mode. Presently, this parameter is ignored by the sqlite
library. The default value for mode is the octal value
0666 and this is the recommended value.
error_messagePassed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.
Returns an SQLiteDatabase object on success, NULL on error.
Example #1 sqlite_factory() example
<?php
$dbhandle = sqlite_factory('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');
/* functionally equivalent to: */
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');
?>
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_fetch_all -- SQLiteResult::fetchAll -- SQLiteUnbuffered::fetchAll — Fetches all rows from a result set as an array of arrays
$result
[, int $result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : arrayObject oriented style (method):
$result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : array$result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : array
sqlite_fetch_all() returns an array of the entire result
set from the result resource. It is similar to calling
sqlite_query() (or
sqlite_unbuffered_query()) and then
sqlite_fetch_array() for each row in the result set.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
result_typeThe optional result_type
parameter accepts a constant and determines how the returned array will be
indexed. Using SQLITE_ASSOC will return only associative
indices (named fields) while SQLITE_NUM will return
only numerical indices (ordinal field numbers). SQLITE_BOTH
will return both associative and numerical indices.
SQLITE_BOTH is the default for this function.
decode_binaryWhen the decode_binary
parameter is set to TRUE (the default), PHP will decode the binary encoding
it applied to the data if it was encoded using the
sqlite_escape_string(). You should normally leave this
value at its default, unless you are interoperating with databases created by
other sqlite capable applications.
Returns an array of the remaining rows in a result set. If called right after sqlite_query(), it returns all rows. If called after sqlite_fetch_array(), it returns the rest. If there are no rows in a result set, it returns an empty array.
The column names returned by
SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the
sqlite.assoc_case configuration
option.
Example #1 Procedural example
<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach ($result as $entry) {
echo 'Name: ' . $entry['name'] . ' E-mail: ' . $entry['email'];
}
?>
Example #2 Object-oriented example
<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set
$result = $query->fetchAll(SQLITE_ASSOC);
foreach ($result as $entry) {
echo 'Name: ' . $entry['name'] . ' E-mail: ' . $entry['email'];
}
?>
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_fetch_array -- SQLiteResult::fetch -- SQLiteUnbuffered::fetch — Fetches the next row from a result set as an array
$result
[, int $result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : arrayObject oriented style (method):
$result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : array$result_type = SQLITE_BOTH
[, bool $decode_binary = TRUE
]] ) : array
Fetches the next row from the given result handle.
If there are no more rows, returns FALSE, otherwise returns an
associative array representing the row data.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
result_typeThe optional result_type
parameter accepts a constant and determines how the returned array will be
indexed. Using SQLITE_ASSOC will return only associative
indices (named fields) while SQLITE_NUM will return
only numerical indices (ordinal field numbers). SQLITE_BOTH
will return both associative and numerical indices.
SQLITE_BOTH is the default for this function.
decode_binaryWhen the decode_binary
parameter is set to TRUE (the default), PHP will decode the binary encoding
it applied to the data if it was encoded using the
sqlite_escape_string(). You should normally leave this
value at its default, unless you are interoperating with databases created by
other sqlite capable applications.
Returns an array of the next row from a result set; FALSE if the
next position is beyond the final row.
The column names returned by
SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the
sqlite.assoc_case configuration
option.
Example #1 Procedural example
<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
while ($entry = sqlite_fetch_array($query, SQLITE_ASSOC)) {
echo 'Name: ' . $entry['name'] . ' E-mail: ' . $entry['email'];
}
?>
Example #2 Object-oriented example
<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set
while ($entry = $query->fetch(SQLITE_ASSOC)) {
echo 'Name: ' . $entry['name'] . ' E-mail: ' . $entry['email'];
}
?>
(PHP 5 < 5.4.0)
sqlite_fetch_column_types -- SQLiteDatabase::fetchColumnTypes — Return an array of column types from a particular table
$table_name
, resource $dbhandle
[, int $result_type = SQLITE_ASSOC
] ) : arrayObject oriented style (method):
$table_name
[, int $result_type = SQLITE_ASSOC
] ) : array
sqlite_fetch_column_types() returns an array of column
data types from the specified table_name table.
table_nameThe table name to query.
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
result_type
The optional result_type parameter accepts a
constant and determines how the returned array will be indexed. Using
SQLITE_ASSOC will return only associative indices
(named fields) while SQLITE_NUM will return only
numerical indices (ordinal field numbers).
SQLITE_ASSOC is the default for
this function.
Returns an array of column data types; FALSE on error.
The column names returned by
SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the
sqlite.assoc_case configuration
option.
| Version | Description |
|---|---|
| 5.1.0 | Added result_type |
Example #1 Procedural example
<?php
$db = sqlite_open('mysqlitedb');
sqlite_query($db, 'CREATE TABLE foo (bar varchar(10), arf text)');
$cols = sqlite_fetch_column_types('foo', $db, SQLITE_ASSOC);
foreach ($cols as $column => $type) {
echo "Column: $column Type: $type\n";
}
?>
Example #2 Object-oriented example
<?php
$db = new SQLiteDatabase('mysqlitedb');
$db->query('CREATE TABLE foo (bar varchar(10), arf text)');
$cols = $db->fetchColumnTypes('foo', SQLITE_ASSOC);
foreach ($cols as $column => $type) {
echo "Column: $column Type: $type\n";
}
?>
The above example will output:
Column: bar Type: VARCHAR Column: arf Type: TEXT
(PHP 5 < 5.4.0)
sqlite_fetch_object -- SQLiteResult::fetchObject -- SQLiteUnbuffered::fetchObject — Fetches the next row from a result set as an object
$result
[, string $class_name
[, array $ctor_params
[, bool $decode_binary = TRUE
]]] ) : objectObject oriented style (method):
$class_name
[, array $ctor_params
[, bool $decode_binary = TRUE
]]] ) : object$class_name
[, array $ctor_params
[, bool $decode_binary = TRUE
]]] ) : objectThis function is currently not documented; only its argument list is available.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.1)
sqlite_fetch_single -- SQLiteResult::fetchSingle -- SQLiteUnbuffered::fetchSingle — Fetches the first column of a result set as a string
$result
[, bool $decode_binary = TRUE
] ) : stringObject oriented style (method):
$decode_binary = TRUE
] ) : string$decode_binary = TRUE
] ) : stringsqlite_fetch_single() is identical to sqlite_fetch_array() except that it returns the value of the first column of the rowset.
This is the most optimal way to retrieve data when you are only interested in the values from a single column of data.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
decode_binaryWhen the decode_binary
parameter is set to TRUE (the default), PHP will decode the binary encoding
it applied to the data if it was encoded using the
sqlite_escape_string(). You should normally leave this
value at its default, unless you are interoperating with databases created by
other sqlite capable applications.
Returns the first column value, as a string.
Example #1 A sqlite_fetch_single() example
<?php
if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {
$sql = "SELECT id FROM sometable WHERE id = 42";
$res = sqlite_query($dbhandle, $sql);
if (sqlite_num_rows($res) > 0) {
echo sqlite_fetch_single($res); // 42
}
sqlite_close($dbhandle);
}
?>
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_fetch_string — Alias of sqlite_fetch_single()
This function is an alias of: sqlite_fetch_single().
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_field_name -- SQLiteResult::fieldName -- SQLiteUnbuffered::fieldName — Returns the name of a particular field
$result
, int $field_index
) : stringObject oriented style (method):
$field_index
) : string$field_index
) : string
Given the ordinal column number, field_index,
sqlite_field_name() returns the name of that field in
the result set result.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
field_indexThe ordinal column number in the result set.
Returns the name of a field in an SQLite result set, given the ordinal
column number; FALSE on error.
The column names returned by
SQLITE_ASSOC and SQLITE_BOTH will be
case-folded according to the value of the
sqlite.assoc_case configuration
option.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_has_more — Finds whether or not more rows are available
$result
) : boolFinds whether more rows are available from the given result set.
resultThe SQLite result resource.
Returns TRUE if there are more rows available from the
result handle, or FALSE otherwise.
(PHP 5 < 5.4.0)
sqlite_has_prev -- SQLiteResult::hasPrev — Returns whether or not a previous row is available
$result
) : boolObject oriented style (method):
Find whether there are more previous rows from the given result handle.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Returns TRUE if there are more previous rows available from the
result handle, or FALSE otherwise.
(PHP 5 >= 5.1.0 < 5.4.0)
sqlite_key -- SQLiteResult::key — Returns the current row index
Object oriented style (method):
SQLiteResult::key() returns the current row index of
the buffered result set result.
Unlike all other SQLite functions, this function does not have a procedural version, and can only be called as a method on a SQLiteResult object.
Returns the current row index of the buffered result set
result.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_last_error -- SQLiteDatabase::lastError — Returns the error code of the last error for a database
$dbhandle
) : intObject oriented style (method):
Returns the error code from the last operation performed on
dbhandle (the database handle), or 0
when no error occurred. A human readable
description of the error code can be retrieved using
sqlite_error_string().
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
Returns an error code, or 0 if no error occurred.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_last_insert_rowid -- SQLiteDatabase::lastInsertRowid — Returns the rowid of the most recently inserted row
$dbhandle
) : intObject oriented style (method):
Returns the rowid of the row that was most recently inserted into the
database dbhandle, if it was created as an
auto-increment field.
You can create auto-increment fields in SQLite by declaring them as
INTEGER PRIMARY KEY in your table schema.
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
Returns the row id, as an integer.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_libencoding — Returns the encoding of the linked SQLite library
The SQLite library may be compiled in either ISO-8859-1
or UTF-8 compatible modes. This function allows you to
determine which encoding scheme is used by your version of the library.
The default PHP distribution builds libsqlite in
ISO-8859-1 encoding
mode. However, this is a misnomer; rather than handling
ISO-8859-1, it operates according to your current
locale settings for string comparisons and sort ordering. So, rather
than ISO-8859-1, you should think of it as being
'8-bit' instead.
When compiled with UTF-8 support, sqlite handles encoding and decoding
of UTF-8 multi-byte character sequences, but does not yet do a complete
job when working with the data (no normalization is performed for
example), and some comparison operations may still not be carried out
correctly.
It is not recommended that you use PHP in a web-server configuration
with a version of the SQLite library compiled with UTF-8 support, since
libsqlite will abort the process if it detects a problem with the
UTF-8 encoding.
Returns the library encoding.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_libversion — Returns the version of the linked SQLite library
Returns the version of the linked SQLite library.
Returns the library version, as a string.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_next -- SQLiteResult::next -- SQLiteUnbuffered::next — Seek to the next row number
$result
) : boolObject oriented style (method):
sqlite_next() advances the result handle
result to the next row.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
Returns TRUE on success, or FALSE if there are no more rows.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_num_fields -- SQLiteResult::numFields -- SQLiteUnbuffered::numFields — Returns the number of fields in a result set
$result
) : intObject oriented style (method):
Returns the number of fields in the result set.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
Returns the number of fields, as an integer.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_num_rows -- SQLiteResult::numRows — Returns the number of rows in a buffered result set
$result
) : intObject oriented style (method):
Returns the number of rows in the buffered result
set.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Returns the number of rows, as an integer.
Example #1 Procedural example
<?php
$db = sqlite_open('mysqlitedb');
$result = sqlite_query($db, "SELECT * FROM mytable WHERE name='John Doe'");
$rows = sqlite_num_rows($result);
echo "Number of rows: $rows";
?>
Example #2 Object-oriented example
<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: $rows";
?>
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_open — Opens an SQLite database and create the database if it does not exist
$filename
[, int $mode = 0666
[, string &$error_message
]] ) : resourceObject oriented style (constructor):
$filename
[, int $mode = 0666
[, string &$error_message
]] )Opens an SQLite database or creates the database if it does not exist.
filenameThe filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.
mode
The mode of the file. Intended to be used to open the database in
read-only mode. Presently, this parameter is ignored by the sqlite
library. The default value for mode is the octal value
0666 and this is the recommended value.
error_messagePassed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.
Returns a resource (database handle) on success, FALSE on error.
Example #1 sqlite_open() example
<?php
if ($db = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {
sqlite_query($db, 'CREATE TABLE foo (bar varchar(10))');
sqlite_query($db, "INSERT INTO foo VALUES ('fnord')");
$result = sqlite_query($db, 'select bar from foo');
var_dump(sqlite_fetch_array($result));
} else {
die($sqliteerror);
}
?>
On Unix platforms, SQLite is sensitive to scripts that use the fork() system call. If you
do have such a script, it is recommended that you close the handle prior
to forking and then re-open it in the child and/or parent.
For more information on this issue, see
» The C language interface
to the SQLite library in the section entitled
Multi-Threading And SQLite.
It is not recommended to work with SQLite databases mounted on NFS partitions. Since NFS is notoriously bad when it comes to locking you may find that you cannot even open the database at all, and if it succeeds, the locking behaviour may be undefined.
Note: Starting with SQLite library version 2.8.2, you can specify
:memory:as thefilenameto create a database that lives only in the memory of the computer. This is useful mostly for temporary processing, as the in-memory database will be destroyed when the process ends. It can also be useful when coupled with theATTACH DATABASESQL statement to load other databases and move and query data between them.
Note: SQLite is safe mode and open_basedir aware.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist
$filename
[, int $mode = 0666
[, string &$error_message
]] ) : resourceThis function behaves identically to sqlite_open() except that is uses the persistent resource mechanism of PHP. For information about the meaning of the parameters, read the sqlite_open() manual page.
sqlite_popen() will first check to see if a persistent
handle has already been opened for the given
filename. If it finds one, it returns that handle
to your script, otherwise it opens a fresh handle to the database.
The benefit of this approach is that you don't incur the performance cost of re-reading the database and index schema on each page hit served by persistent web server SAPI's (any SAPI except for regular CGI or CLI).
Note: If you use persistent handles and have the database updated by a background process (perhaps via a crontab), and that process re-creates the database by overwriting it (either by unlinking and rebuilding, or moving the updated version to replace the current version), you may experience undefined behaviour when a persistent handle on the old version of the database is recycled. To avoid this situation, have your background processes open the same database file and perform their updates in a transaction.
filenameThe filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.
mode
The mode of the file. Intended to be used to open the database in
read-only mode. Presently, this parameter is ignored by the sqlite
library. The default value for mode is the octal value
0666 and this is the recommended value.
error_messagePassed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.
Returns a resource (database handle) on success, FALSE on error.
(PHP 5 < 5.4.0)
sqlite_prev -- SQLiteResult::prev — Seek to the previous row number of a result set
$result
) : boolObject oriented style (method):
sqlite_prev() seeks back the
result handle to the previous row.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Returns TRUE on success, or FALSE if there are no more previous rows.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_query -- SQLiteDatabase::query — Executes a query against a given database and returns a result handle
$dbhandle
, string $query
[, int $result_type = SQLITE_BOTH
[, string &$error_msg
]] ) : resource$query
, resource $dbhandle
[, int $result_type = SQLITE_BOTH
[, string &$error_msg
]] ) : resourceObject oriented style (method):
$query
[, int $result_type = SQLITE_BOTH
[, string &$error_msg
]] ) : SQLiteResult
Executes an SQL statement given by the query against
a given database handle.
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
queryThe query to be executed.
Data inside the query should be properly escaped.
result_typeThe optional result_type
parameter accepts a constant and determines how the returned array will be
indexed. Using SQLITE_ASSOC will return only associative
indices (named fields) while SQLITE_NUM will return
only numerical indices (ordinal field numbers). SQLITE_BOTH
will return both associative and numerical indices.
SQLITE_BOTH is the default for this function.
error_msgThe specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.
Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the
dbhandleparameter is the first parameter to the function.
This function will return a result handle or FALSE on failure.
For queries that return rows, the result handle can then be used with
functions such as sqlite_fetch_array() and
sqlite_seek().
Regardless of the query type, this function will return FALSE if the
query failed.
sqlite_query() returns a buffered, seekable result handle. This is useful for reasonably small queries where you need to be able to randomly access the rows. Buffered result handles will allocate memory to hold the entire result and will not return until it has been fetched. If you only need sequential access to the data, it is recommended that you use the much higher performance sqlite_unbuffered_query() instead.
| Version | Description |
|---|---|
| 5.1.0 |
Added the error_msg parameter
|
SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script. However, this works only when the result of the function is not used - if it is used, only the first SQL statement would be executed. Function sqlite_exec() will always execute multiple SQL statements.
When executing multiple queries, the return value of this function
will be FALSE if there was an error, but undefined otherwise (it might
be TRUE for success or it might return a result handle).
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_rewind -- SQLiteResult::rewind — Seek to the first row number
$result
) : boolObject oriented style (method):
sqlite_rewind() seeks back to the first row in the given result set.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Returns FALSE if there are no rows in the result set, TRUE otherwise.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_seek -- SQLiteResult::seek — Seek to a particular row number of a buffered result set
$result
, int $rownum
) : boolObject oriented style (method):
$rownum
) : bool
sqlite_seek() seeks to the row given by the parameter
rownum.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
rownumThe ordinal row number to seek to. The row number is zero-based (0 is the first row).
Note:
This function cannot be used with unbuffered result handles.
Returns FALSE if the row does not exist, TRUE otherwise.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.1)
sqlite_single_query -- SQLiteDatabase::singleQuery — Executes a query and returns either an array for one single column or the value of the first row
$db
, string $query
[, bool $first_row_only
[, bool $decode_binary
]] ) : arrayObject oriented style (method):
$query
[, bool $first_row_only
[, bool $decode_binary
]] ) : arrayThis function is currently not documented; only its argument list is available.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF
$data
) : stringDecodes binary data passed as parameters to a UDF.
You must call this function on parameters passed to your UDF if you need them to handle binary data, as the binary encoding employed by PHP will obscure the content and of the parameter in its natural, non-coded form.
PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.
dataThe encoded data that will be decoded, data that was applied by either sqlite_udf_encode_binary() or sqlite_escape_string().
The decoded string.
Example #1 binary-safe max_length aggregation function example
<?php
$data = array(
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
);
$db = sqlite_open(':memory:');
sqlite_query($db, "CREATE TABLE strings(a)");
foreach ($data as $str) {
$str = sqlite_escape_string($str);
sqlite_query($db, "INSERT INTO strings VALUES ('$str')");
}
function max_len_step(&$context, $string)
{
$string = sqlite_udf_decode_binary($string);
if (strlen($string) > $context) {
$context = strlen($string);
}
}
function max_len_finalize(&$context)
{
return $context;
}
sqlite_create_aggregate($db, 'max_len', 'max_len_step', 'max_len_finalize');
var_dump(sqlite_array_query($db, 'SELECT max_len(a) from strings'));
?>
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_udf_encode_binary — Encode binary data before returning it from an UDF
$data
) : string
sqlite_udf_encode_binary() applies a binary encoding
to the data so that it can be safely returned from
queries (since the underlying libsqlite API is not binary safe).
If there is a chance that your data might be binary unsafe (e.g.: it
contains a NUL byte in the middle rather than at the end, or if it has and
0x01 byte as the first character) then you must
call this function to encode the return value from your UDF.
PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.
Note:
Do not use sqlite_escape_string() to quote strings returned from UDF's as it will lead to double-quoting of the data. Use sqlite_udf_encode_binary() instead!
The encoded string.
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_unbuffered_query -- SQLiteDatabase::unbufferedQuery — Execute a query that does not prefetch and buffer all data
$dbhandle
, string $query
[, int $result_type = SQLITE_BOTH
[, string &$error_msg
]] ) : resource$query
, resource $dbhandle
[, int $result_type = SQLITE_BOTH
[, string &$error_msg
]] ) : resourceObject oriented style (method):
$query
[, int $result_type = SQLITE_BOTH
[, string &$error_msg
]] ) : SQLiteUnbufferedsqlite_unbuffered_query() is identical to sqlite_query() except that the result that is returned is a sequential forward-only result set that can only be used to read each row, one after the other.
This function is ideal for generating things such as HTML tables where you only need to process one row at a time and don't need to randomly access the row data.
Note:
Functions such as sqlite_seek(), sqlite_rewind(), sqlite_next(), sqlite_current(), and sqlite_num_rows() do not work on result handles returned from sqlite_unbuffered_query().
dbhandleThe SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.
queryThe query to be executed.
Data inside the query should be properly escaped.
result_typeThe optional result_type
parameter accepts a constant and determines how the returned array will be
indexed. Using SQLITE_ASSOC will return only associative
indices (named fields) while SQLITE_NUM will return
only numerical indices (ordinal field numbers). SQLITE_BOTH
will return both associative and numerical indices.
SQLITE_BOTH is the default for this function.
error_msgThe specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.
Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the
dbhandleparameter is the first parameter to the function.
Returns a result handle or FALSE on failure.
sqlite_unbuffered_query() returns a sequential forward-only result set that can only be used to read each row, one after the other.
| Version | Description |
|---|---|
| 5.1.0 |
Added the error_msg parameter
|
(PHP 5 < 5.4.0)
sqlite_valid -- SQLiteResult::valid -- SQLiteUnbuffered::valid — Returns whether more rows are available
$result
) : boolObject oriented style (method):
Finds whether more rows are available from the given result handle.
resultThe SQLite result resource. This parameter is not required when using the object-oriented method.
Note:
This function cannot be used with unbuffered result handles.
Returns TRUE if there are more rows available from the
result handle, or FALSE otherwise.
Support for SQLite version 3 databases.
As of PHP 7.4.0 » libsqlite ≥ 3.7.4 is required. Formerly, the bundled libsqlite could have been used instead.
The SQLite3 extension is enabled by default as of PHP 5.3.0. It's
possible to disable it by using --without-sqlite3
at compile time.
Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with Windows distributions of PHP as of PHP 5.3.0.
Note: Additional setup on Windows as of PHP 7.4.0
In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libsqlite3.dll.
Note:
This extension was briefly a PECL extension but that version is only recommended for experimental use.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| sqlite3.extension_dir | "" | PHP_INI_SYSTEM | Available as of PHP 5.3.11. |
| sqlite3.defensive | 1 | PHP_INI_SYSTEM | Available as of PHP 7.2.17 and 7.3.4 for libsqlite ≥ 3.26.0. |
Here's a short explanation of the configuration directives.
sqlite3.extension_dir
string
Path to the directory where the loadable extensions for SQLite reside.
sqlite3.defensive
bool
When the defensive flag is enabled, language features that allow ordinary SQL to deliberately corrupt the database file are disabled. This forbids writing directly to the schema, shadow tables (eg. FTS data tables), or the sqlite_dbpage virtual table. This php.ini setting is only effective for libsqlite ≥ 3.26.0.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
SQLITE3_ASSOC
(integer)
SQLITE3_NUM
(integer)
SQLITE3_BOTH
(integer)
SQLITE3_INTEGER
(integer)
SQLITE3_FLOAT
(integer)
SQLITE3_TEXT
(integer)
SQLITE3_BLOB
(integer)
SQLITE3_NULL
(integer)
SQLITE3_OPEN_READONLY
(integer)
SQLITE3_OPEN_READWRITE
(integer)
SQLITE3_OPEN_CREATE
(integer)
SQLITE3_DETERMINISTIC
(integer)
(PHP 5 >= 5.3.0, PHP 7)
A class that interfaces SQLite 3 databases.
$destination_db
[, string $source_dbname = "main"
[, string $destination_dbname = "main"
]] ) : bool$filename
[, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE
[, string $encryption_key = ""
]] )$name
, mixed $step_callback
, mixed $final_callback
[, int $argument_count = -1
] ) : bool$name
, mixed $callback
[, int $argument_count = -1
[, int $flags = 0
]] ) : bool$filename
[, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE
[, string $encryption_key = ""
]] ) : void$table
, string $column
, int $rowid
[, string $dbname = "main"
[, int $flags = SQLITE3_OPEN_READONLY
]] ) : resource(PHP 7 >= 7.4.0)
SQLite3::backup — Backup one database to another database
$destination_db
[, string $source_dbname = "main"
[, string $destination_dbname = "main"
]] ) : boolSQLite3::backup() copies the contents of one database into another, overwriting the contents of the destination database. It is useful either for creating backups of databases or for copying in-memory databases to or from persistent files.
destination_dbA database connection opened with SQLite3::open().
source_dbname
The database name is "main" for the main database,
"temp" for the temporary database,
or the name specified after the AS keyword
in an ATTACH statement for an attached database.
destination_dbname
Analogous to source_dbname
but for the destination_db.
Returns TRUE on success or FALSE on failure.
Example #1 Backup an existing database
<?php
// $conn is a connection to an already opened sqlite3 database
$backup = new SQLite3('backup.sqlite');
$conn->backup($backup);
?>
(PHP 5 >= 5.3.3, PHP 7)
SQLite3::busyTimeout — Sets the busy connection handler
$msecs
) : boolSets a busy handler that will sleep until the database is not locked or the timeout is reached.
msecsThe milliseconds to sleep. Setting this value to a value less than or equal to zero, will turn off an already set timeout handler.
Returns TRUE on success, or FALSE on failure.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement.
This function has no parameters.
Returns an integer value corresponding to the number of database rows changed (or inserted or deleted) by the most recent SQL statement.
Example #1 SQLite3::changes() example
<?php
$db = new SQLite3('mysqlitedb.db');
$query = $db->exec('UPDATE counter SET views=0 WHERE page="test"');
if ($query) {
echo 'Number of rows modified: ', $db->changes();
}
?>
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::close — Closes the database connection
Closes the database connection.
This function has no parameters.
Returns TRUE on success or FALSE on failure.
Example #1 SQLite3::close() example
<?php
$db = new SQLite3('mysqlitedb.db');
$db->close();
?>
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
$filename
[, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE
[, string $encryption_key = ""
]] )Instantiates an SQLite3 object and opens a connection to an SQLite 3 database. If the build includes encryption, then it will attempt to use the key.
filename
Path to the SQLite database, or :memory: to use in-memory database.
If filename is an empty string, then a private, temporary on-disk
database will be created. This private database will be automatically
deleted as soon as the database connection is closed.
flags
Optional flags used to determine how to open the SQLite database. By
default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.
SQLITE3_OPEN_READONLY: Open the database for
reading only.
SQLITE3_OPEN_READWRITE: Open the database for
reading and writing.
SQLITE3_OPEN_CREATE: Create the database if it
does not exist.
encryption_keyAn optional encryption key used when encrypting and decrypting an SQLite database. If the SQLite encryption module is not installed, this parameter will have no effect.
Returns an SQLite3 object on success.
Throws an Exception on failure.
| Version | Description |
|---|---|
| 7.0.10 |
The filename can now be empty to use a private,
temporary on-disk database.
|
Example #1 SQLite3::__construct() example
<?php
$db = new SQLite3('mysqlitedb.db');
$db->exec('CREATE TABLE foo (bar TEXT)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
$name
, mixed $step_callback
, mixed $final_callback
[, int $argument_count = -1
] ) : boolRegisters a PHP function or user-defined function for use as an SQL aggregate function for use within SQL statements.
nameName of the SQL aggregate to be created or redefined.
step_callbackCallback function called for each row of the result set. Your PHP function should accumulate the result and store it in the aggregation context.
This function need to be defined as:
context
NULL for the first row; on subsequent rows it will have the value
that was previously returned from the step function; you should use
this to maintain the aggregate state.
rownumberThe current row number.
value1The first argument passed to the aggregate.
...Further arguments passed to the aggregate.
context argument in the next call of the step or
finalize functions.
final_callbackCallback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. This callback function should return a type understood by SQLite (i.e. scalar type).
This function need to be defined as:
contextHolds the return value from the very last call to the step function.
rownumber
Always 0.
argument_countThe number of arguments that the SQL aggregate takes. If this parameter is negative, then the SQL aggregate may take any number of arguments.
Returns TRUE upon successful creation of the aggregate, or FALSE on failure.
Example #1 max_length aggregation function example
<?php
$data = array(
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
);
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
$insert->bindValue(1, $str);
$insert->execute();
}
$insert = null;
function max_len_step($context, $rownumber, $string)
{
if (strlen($string) > $context) {
$context = strlen($string);
}
return $context;
}
function max_len_finalize($context, $rownumber)
{
return $context === null ? 0 : $context;
}
$db->createAggregate('max_len', 'max_len_step', 'max_len_finalize');
var_dump($db->querySingle('SELECT max_len(a) from strings'));
?>
The above example will output:
int(5)
In this example, we are creating an aggregating function that will
calculate the length of the longest string in one of the columns of the
table. For each row, the max_len_step function is
called and passed a $context parameter. The context
parameter is just like any other PHP variable and be set to hold an array
or even an object value. In this example, we are simply using it to hold
the maximum length we have seen so far; if the
$string has a length longer than the current
maximum, we update the context to hold this new maximum length.
After all of the rows have been processed, SQLite calls the
max_len_finalize function to determine the aggregate
result. Here, we could perform some kind of calculation based on the
data found in the $context. In our simple example
though, we have been calculating the result as the query progressed, so we
simply need to return the context value.
It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.
You can use SQLite3::createAggregate() to override SQLite native SQL functions.
(PHP 5 >= 5.3.11, PHP 7)
SQLite3::createCollation — Registers a PHP function for use as an SQL collating function
Registers a PHP function or user-defined function for use as a collating function within SQL statements.
nameName of the SQL collating function to be created or redefined
callbackThe name of a PHP function or user-defined function to apply as a callback, defining the behavior of the collation. It should accept two values and return as strcmp() does, i.e. it should return -1, 1, or 0 if the first string sorts before, sorts after, or is equal to the second.
This function need to be defined as:
Returns TRUE on success or FALSE on failure.
Example #1 SQLite3::createCollation() example
Register the PHP function strnatcmp() as a collating sequence in the SQLite3 database.
<?php
$db = new SQLite3(":memory:");
$db->exec("CREATE TABLE test (col1 string)");
$db->exec("INSERT INTO test VALUES ('a1')");
$db->exec("INSERT INTO test VALUES ('a10')");
$db->exec("INSERT INTO test VALUES ('a2')");
$db->createCollation('NATURAL_CMP', 'strnatcmp');
$defaultSort = $db->query("SELECT col1 FROM test ORDER BY col1");
$naturalSort = $db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP");
echo "default:\n";
while ($row = $defaultSort->fetchArray()){
echo $row['col1'], "\n";
}
echo "\nnatural:\n";
while ($row = $naturalSort->fetchArray()){
echo $row['col1'], "\n";
}
$db->close();
?>
The above example will output:
default: a1 a10 a2 natural: a1 a2 a10
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
$name
, mixed $callback
[, int $argument_count = -1
[, int $flags = 0
]] ) : boolRegisters a PHP function or user-defined function for use as an SQL scalar function for use within SQL statements.
nameName of the SQL function to be created or redefined.
callbackThe name of a PHP function or user-defined function to apply as a callback, defining the behavior of the SQL function.
This function need to be defined as:
value1The first argument passed to the SQL function.
...Further arguments passed to the SQL function.
argument_count
The number of arguments that the SQL function takes. If
this parameter is -1, then the SQL function may take
any number of arguments.
flags
A bitwise conjunction of flags. Currently, only
SQLITE3_DETERMINISTIC is supported, which specifies
that the function always returns the same result given the same inputs
within a single SQL statement.
Returns TRUE upon successful creation of the function, FALSE on failure.
| Version | Description |
|---|---|
| 7.1.4 |
The flags parameter has been added.
|
Example #1 SQLite3::createFunction() example
<?php
function my_udf_md5($string) {
return md5($string);
}
$db = new SQLite3('mysqlitedb.db');
$db->createFunction('my_udf_md5', 'my_udf_md5');
var_dump($db->querySingle('SELECT my_udf_md5("test")'));
?>
The above example will output something similar to:
string(32) "098f6bcd4621d373cade4e832627b4f6"
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::enableExceptions — Enable throwing exceptions
$enableExceptions = FALSE
] ) : boolControls whether the SQLite3 instance will throw exceptions or warnings on error.
enable
When TRUE, the SQLite3 instance, and
SQLite3Stmt and SQLite3Result
instances derived from it, will throw exceptions on error.
When FALSE, the SQLite3 instance, and
SQLite3Stmt and SQLite3Result
instances derived from it, will raise warnings on error.
For either mode, the error code and message, if any, will be available via SQLite3::lastErrorCode() and SQLite3::lastErrorMsg() respectively.
Returns the old value; TRUE if exceptions were enabled, FALSE otherwise.
Example #1 SQLite3::enableExceptions() example
<?php
$sqlite = new SQLite3(':memory:');
try {
$sqlite->exec('create table foo');
$sqlite->enableExceptions(true);
$sqlite->exec('create table bar');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>
The above example will output something similar to:
Warning: SQLite3::exec(): near "foo": syntax error in example.php on line 4 Caught exception: near "bar": syntax error
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::escapeString — Returns a string that has been properly escaped
$value
) : stringReturns a string that has been properly escaped for safe inclusion in an SQL statement.
This function is not (yet) binary safe!
To properly handle BLOB fields which may contain NUL characters, use SQLite3Stmt::bindParam() instead.
valueThe string to be escaped.
Returns a properly escaped string that may be used safely in an SQL statement.
addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::exec — Executes a result-less query against a given database
$query
) : boolExecutes a result-less query against a given database.
Note: SQLite3 may need to create » temporary files during the execution of queries, so the respective directories may have to be writable.
queryThe SQL query to execute (typically an INSERT, UPDATE, or DELETE query).
Returns TRUE if the query succeeded, FALSE on failure.
Example #1 SQLite3::exec() example
<?php
$db = new SQLite3('mysqlitedb.db');
$db->exec('CREATE TABLE bar (bar STRING)');
?>
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
Returns the numeric result code of the most recent failed SQLite request.
This function has no parameters.
Returns an integer value representing the numeric result code of the most recent failed SQLite request.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
Returns English text describing the most recent failed SQLite request.
This function has no parameters.
Returns an English string describing the most recent failed SQLite request.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
Returns the row ID of the most recent INSERT into the database.
This function has no parameters.
Returns the row ID of the most recent INSERT into the database
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::loadExtension — Attempts to load an SQLite extension library
$shared_library
) : boolAttempts to load an SQLite extension library.
shared_libraryThe name of the library to load. The library must be located in the directory specified in the configure option sqlite3.extension_dir.
Returns TRUE if the extension is successfully loaded, FALSE on failure.
Example #1 SQLite3::loadExtension() example
<?php
$db = new SQLite3('mysqlitedb.db');
$db->loadExtension('libagg.so');
?>
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::open — Opens an SQLite database
$filename
[, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE
[, string $encryption_key = ""
]] ) : voidOpens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.
filename
Path to the SQLite database, or :memory: to use in-memory database.
flags
Optional flags used to determine how to open the SQLite database. By
default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.
SQLITE3_OPEN_READONLY: Open the database for
reading only.
SQLITE3_OPEN_READWRITE: Open the database for
reading and writing.
SQLITE3_OPEN_CREATE: Create the database if it
does not exist.
encryption_keyAn optional encryption key used when encrypting and decrypting an SQLite database. If the SQLite encryption module is not installed, this parameter will have no effect.
No value is returned.
Example #1 SQLite3::open() example
<?php
/**
* Simple example of extending the SQLite3 class and changing the __construct
* parameters, then using the open method to initialize the DB.
*/
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mysqlitedb.db');
}
}
$db = new MyDB();
$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::openBlob — Opens a stream resource to read a BLOB
$table
, string $column
, int $rowid
[, string $dbname = "main"
[, int $flags = SQLITE3_OPEN_READONLY
]] ) : resourceOpens a stream resource to read or write a BLOB, which would be selected by:
SELECT column FROM dbname.table WHERE rowid = rowid
Note: It is not possible to change the size of a BLOB by writing to the stream. Instead, an UPDATE statement has to be executed, possibly using SQLite's zeroblob() function to set the desired BLOB size.
tableThe table name.
columnThe column name.
rowidThe row ID.
dbnameThe symbolic name of the DB
flags
Either SQLITE3_OPEN_READONLY or
SQLITE3_OPEN_READWRITE to open the stream
for reading only, or for reading and writing, respectively.
Returns a stream resource, or FALSE on failure.
| Version | Description |
|---|---|
| 7.2.0 |
The flags parameter has been added, allowing to
write BLOBs; formerly only reading was supported.
|
Example #1 SQLite3::openBlob() example
<?php
$conn = new SQLite3(':memory:');
$conn->exec('CREATE TABLE test (text text)');
$conn->exec("INSERT INTO test VALUES ('Lorem ipsum')");
$stream = $conn->openBlob('test', 'text', 1);
echo stream_get_contents($stream);
fclose($stream); // mandatory, otherwise the next line would fail
$conn->close();
?>
The above example will output:
Lorem ipsum
Example #2 Incrementally writing a BLOB
<?php
$conn = new SQLite3(':memory:');
$conn->exec('CREATE TABLE test (text text)');
$conn->exec("INSERT INTO test VALUES (zeroblob(36))");
$stream = $conn->openBlob('test', 'text', 1, 'main', SQLITE3_OPEN_READWRITE);
for ($i = 0; $i < 3; $i++) {
fwrite($stream, "Lorem ipsum\n");
}
fclose($stream);
echo $conn->querySingle("SELECT text FROM test");
$conn->close();
?>
The above example will output:
Lorem ipsum Lorem ipsum Lorem ipsum
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::prepare — Prepares an SQL statement for execution
Prepares an SQL statement for execution and returns an SQLite3Stmt object.
queryThe SQL query to prepare.
Returns an SQLite3Stmt object on success or FALSE on failure.
Example #1 SQLite3::prepare() example
<?php
unlink('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');
$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");
$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);
$result = $stmt->execute();
var_dump($result->fetchArray());
?>
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::query — Executes an SQL query
Executes an SQL query, returning an SQLite3Result object. If the query does not yield a result (such as DML statements) the returned SQLite3Result object is not really usable. Use SQLite3::exec() for such queries instead.
queryThe SQL query to execute.
Returns an SQLite3Result object, or FALSE on failure.
Example #1 SQLite3::query() example
<?php
$db = new SQLite3('mysqlitedb.db');
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::querySingle — Executes a query and returns a single result
Executes a query and returns a single result.
queryThe SQL query to execute.
entire_row
By default, querySingle() returns the value of the
first column returned by the query. If
entire_row is TRUE, then it returns an array
of the entire first row.
Returns the value of the first column of results or an array of the entire
first row (if entire_row is TRUE).
If the query is valid but no results are returned, then NULL will be
returned if entire_row is FALSE, otherwise an
empty array is returned.
Invalid or failing queries will return FALSE.
Example #1 SQLite3::querySingle() example
<?php
$db = new SQLite3('mysqlitedb.db');
var_dump($db->querySingle('SELECT username FROM user WHERE userid=1'));
print_r($db->querySingle('SELECT username, email FROM user WHERE userid=1', true));
?>
The above example will output something similar to:
string(5) "Scott"
Array
(
[username] => Scott
[email] => scott@example.com
)
(PHP 5 >= 5.3.0, PHP 7)
SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
Returns the SQLite3 library version as a string constant and as a number.
This function has no parameters.
Returns an associative array with the keys "versionString" and "versionNumber".
Example #1 SQLite3::version() example
<?php
print_r(SQLite3::version());
?>
The above example will output something similar to:
Array
(
[versionString] => 3.5.9
[versionNumber] => 3005009
)
(PHP 5 >= 5.3.0, PHP 7)
A class that handles prepared statements for the SQLite 3 extension.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Stmt::bindParam — Binds a parameter to a statement variable
Binds a parameter to a statement variable.
Before PHP 7.2.14 and 7.3.0, respectively, SQLite3Stmt::reset() must be called after the first call to SQLite3Stmt::execute() if the bound value should be properly updated on following calls to SQLite3Stmt::execute(). If SQLite3Stmt::reset() is not called, the bound value will not change, even if the value assigned to the variable passed to SQLite3Stmt::bindParam() has changed, or SQLite3Stmt::bindParam() has been called again.
sql_param
Either a string (for named parameters) or an int
(for positional parameters) identifying the statement variable to which the
value should be bound.
If a named parameter does not start with a colon (:) or an
at sign (@), a colon (:) is automatically preprended.
Positional parameters start with 1.
paramThe parameter to bind to a statement variable.
typeThe data type of the parameter to bind.
SQLITE3_INTEGER: The value is a signed integer,
stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of
the value.
SQLITE3_FLOAT: The value is a floating point
value, stored as an 8-byte IEEE floating point number.
SQLITE3_TEXT: The value is a text string, stored
using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).
SQLITE3_BLOB: The value is a blob of data, stored
exactly as it was input.
SQLITE3_NULL: The value is a NULL value.
As of PHP 7.0.7, if type is omitted, it is automatically
detected from the type of the param: boolean
and integer are treated as SQLITE3_INTEGER,
float as SQLITE3_FLOAT, null
as SQLITE3_NULL and all others as SQLITE3_TEXT.
Formerly, if type has been omitted, it has defaulted
to SQLITE3_TEXT.
Note:
If
paramisNULL, it is always treated asSQLITE3_NULL, regardless of the giventype.
Returns TRUE if the parameter is bound to the statement variable, FALSE
on failure.
| Version | Description |
|---|---|
| 7.4.0 |
sql_param now also supports the @param
notation.
|
Example #1 SQLite3Stmt::bindParam() Usage
This example shows how a single prepared statement with a single parameter binding can be used to insert multiple rows with different values.
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE foo (bar TEXT)");
$stmt = $db->prepare("INSERT INTO foo VALUES (:bar)");
$stmt->bindParam(':bar', $bar, SQLITE3_TEXT);
$bar = 'baz';
$stmt->execute();
$bar = 42;
$stmt->execute();
$res = $db->query("SELECT * FROM foo");
while (($row = $res->fetchArray(SQLITE3_ASSOC))) {
var_dump($row);
}
?>
The above example will output:
array(1) {
["bar"]=>
string(3) "baz"
}
array(1) {
["bar"]=>
string(2) "42"
}
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
Binds the value of a parameter to a statement variable.
Before PHP 7.2.14 and 7.3.0, respectively, once the statement has been executed, SQLite3Stmt::reset() needs to be called to be able to change the value of bound parameters.
sql_param
Either a string (for named parameters) or an int
(for positional parameters) identifying the statement variable to which the
value should be bound.
If a named parameter does not start with a colon (:) or an
at sign (@), a colon (:) is automatically preprended.
Positional parameters start with 1.
valueThe value to bind to a statement variable.
typeThe data type of the value to bind.
SQLITE3_INTEGER: The value is a signed integer,
stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of
the value.
SQLITE3_FLOAT: The value is a floating point
value, stored as an 8-byte IEEE floating point number.
SQLITE3_TEXT: The value is a text string, stored
using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).
SQLITE3_BLOB: The value is a blob of data, stored
exactly as it was input.
SQLITE3_NULL: The value is a NULL value.
As of PHP 7.0.7, if type is omitted, it is automatically
detected from the type of the value: boolean
and integer are treated as SQLITE3_INTEGER,
float as SQLITE3_FLOAT, null
as SQLITE3_NULL and all others as SQLITE3_TEXT.
Formerly, if type has been omitted, it has defaulted
to SQLITE3_TEXT.
Note:
If
valueisNULL, it is always treated asSQLITE3_NULL, regardless of the giventype.
Returns TRUE if the value is bound to the statement variable, or FALSE on failure.
| Version | Description |
|---|---|
| 7.4.0 |
sql_param now also supports the @param
notation.
|
Example #1 SQLite3Stmt::bindValue() example
<?php
$db = new SQLite3(':memory:');
$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");
$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);
$result = $stmt->execute();
var_dump($result->fetchArray(SQLITE3_ASSOC));
?>
The above example will output:
array(1) {
["bar"]=>
string(14) "This is a test"
}
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Stmt::clear — Clears all current bound parameters
Clears all current bound parameters (sets them to NULL).
This method needs to be used with SQLite3Stmt::reset().
If used alone, any call to
SQLite3Stmt::bindValue() or
SQLite3Stmt::bindParam() will be of no effect
and all bound parameters will have the NULL value.
This function has no parameters.
Returns TRUE on successful clearing of bound parameters, FALSE on
failure.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Stmt::close — Closes the prepared statement
Closes the prepared statement.
Note: Note that all SQLite3Results that have been retrieved by executing this statement will be invalidated when the statement is closed.
This function has no parameters.
Returns TRUE
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
Executes a prepared statement and returns a result set object.
Result set objects retrieved by calling this method on the same statement object are not independent, but rather share the same underlying structure. Therefore it is recommended to call SQLite3Result::finalize(), before calling SQLite3Stmt::execute() on the same statement object again.
This function has no parameters.
Returns an SQLite3Result object on successful execution of the prepared
statement, FALSE on failure.
(PHP 7 >= 7.4.0)
SQLite3Stmt::getSQL — Get the SQL of the statement
$expanded = FALSE
] ) : string
Retrieves the SQL of the prepared statement. If expanded
is FALSE, the unmodified SQL is retrieved. If expanded
is TRUE, all query parameters are replaced with their bound values, or with
an SQL NULL, if not already bound.
expanded
Whether to retrieve the expanded SQL. Passing TRUE is only supported as
of libsqlite 3.14.
Returns the SQL of the prepared statement, or FALSE on failure.
If expanded is TRUE, but the libsqlite version is less
than 3.14, an error of level E_WARNING or an Exception
is issued, according to SQLite3::enableExceptions().
Example #1 Inspecting the expanded SQL
<?php
$db = new SQLite3(':memory:');
$stmt = $db->prepare("SELECT :a, ?, :c");
$stmt->bindValue(':a', 'foo');
$answer = 42;
$stmt->bindParam(2, $answer);
var_dump($stmt->getSQL(true));
?>
The above example will output something similar to:
string(24) "SELECT 'foo', '42', NULL"
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
Returns the number of parameters within the prepared statement.
This function has no parameters.
Returns the number of parameters within the prepared statement.
(PHP 5 >= 5.3.6, PHP 7)
SQLite3Stmt::readOnly — Returns whether a statement is definitely read only
Returns whether a statement is definitely read only. A statement is considered read only, if it makes no direct changes to the content of the database file. Note that user defined SQL functions might change the database indirectly as a side effect.
This function has no parameters.
Returns TRUE if a statement is definitely read only, FALSE otherwise.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Stmt::reset — Resets the prepared statement
Resets the prepared statement to its state prior to execution. All bindings remain intact after reset.
This function has no parameters.
Returns TRUE if the statement is successfully reset, or FALSE on failure.
(PHP 5 >= 5.3.0, PHP 7)
A class that handles result sets for the SQLite 3 extension.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Result::columnName — Returns the name of the nth column
$column_number
) : string
Returns the name of the column specified by the
column_number.
Note that the name of a result column is the value of the AS clause
for that column, if there is an AS clause. If there is no AS
clause then the name of the column is unspecified and may change from one release of libsqlite3
to the next.
column_numberThe numeric zero-based index of the column.
Returns the string name of the column identified by
column_number.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Result::columnType — Returns the type of the nth column
$column_number
) : int
Returns the type of the column identified by
column_number.
column_numberThe numeric zero-based index of the column.
Returns the data type index of the column identified by
column_number (one of
SQLITE3_INTEGER, SQLITE3_FLOAT,
SQLITE3_TEXT, SQLITE3_BLOB, or
SQLITE3_NULL).
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
$mode = SQLITE3_BOTH
] ) : arrayFetches a result row as an associative or numerically indexed array or both. By default, fetches as both.
mode
Controls how the next row will be returned to the caller. This value
must be one of either SQLITE3_ASSOC,
SQLITE3_NUM, or SQLITE3_BOTH.
SQLITE3_ASSOC: returns an array indexed by column
name as returned in the corresponding result set
SQLITE3_NUM: returns an array indexed by column
number as returned in the corresponding result set, starting at
column 0
SQLITE3_BOTH: returns an array indexed by both
column name and number as returned in the corresponding result set,
starting at column 0
Returns a result row as an associatively or numerically indexed array or
both. Alternately will return FALSE if there are no more rows.
The types of the values of the returned array are mapped from SQLite3 types
as follows: integers are mapped to integer if they fit into the
range PHP_INT_MIN..PHP_INT_MAX, and
to string otherwise. Floats are mapped to float,
NULL values are mapped to null, and strings
and blobs are mapped to string.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Result::finalize — Closes the result set
Closes the result set.
This function has no parameters.
Returns TRUE.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Result::numColumns — Returns the number of columns in the result set
Returns the number of columns in the result set.
This function has no parameters.
Returns the number of columns in the result set.
(PHP 5 >= 5.3.0, PHP 7)
SQLite3Result::reset — Resets the result set back to the first row
Resets the result set back to the first row.
This function has no parameters.
Returns TRUE if the result set is successfully reset
back to the first row, FALSE on failure.
The SQLSRV extension allows you to access Microsoft SQL Server and SQL Azure databases. The 3.0 release of the driver supports SQL Server, beginning with SQL Server 2005, including SQL Server 2012 and SQL Server 2012 LocalDB. (For more information about LocalDB, see » PHP Driver for SQL Server Support for LocalDB and » SQL Server 2012 Express LocalDB.)
The SQLSRV extension is supported by Microsoft and available for download here: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx. SQL Server 2012 LocalDB can be downloaded here: » http://go.microsoft.com/fwlink/?LinkID=237665.
The SQLSRV extension can be used on the following operating systems:
The SQLSRV extension requires that the Microsoft SQL Server 2012 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2012 Native Client is not already installed, click the appropriate link below to download it:
The SQLSRV download comes 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.
The most recent version of the driver is available for download here: » SQLSRV 4.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.
For more information about SQLSRV requirements, see » SQLSRV System Requirements.
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.
The most recent version of the driver is available for download here: » SQLSRV 4.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.
For more information about SQLSRV requirements, see » SQLSRV System Requirements.
The SQLSRV extension is only compatible with PHP 5 running on Windows. Since version 4.0 the SQLSRV extension is compatilbe only with PHP 7.0 running on Linux or Windows.
The behaviour of these functions is affected by settings in php.ini.
The following table lists the configuration options available in the SQLSRV extension. For more information about these options, see » Handling SQLSRV Warnings and Errors.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| sqlsrv.WarningsReturnAsErrors | 1 (TRUE) |
PHP_INI_ALL | Available since SQLSRV 1.0 |
| sqlsrv.LogSubsystems | 0 | PHP_INI_ALL | Available since SQLSRV 1.0 |
| sqlsrv.LogSeverity | 1 | PHP_INI_ALL | Available since SQLSRV 1.0 |
A connection resource returned by sqlsrv_connect().
A statement resource returned by sqlsrv_query() or by sqlsrv_prepare().
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
SQLSRV_FETCH_ASSOC
(integer)
SQLSRV_FETCH_NUMERIC
(integer)
SQLSRV_FETCH_BOTH
(integer)
SQLSRV_ERR_ALL
(integer)
SQLSRV_ERR_ERRORS
(integer)
SQLSRV_ERR_WARNINGS
(integer)
SQLSRV_LOG_SYSTEM_ALL
(integer)
SQLSRV_LOG_SYSTEM_CONN
(integer)
SQLSRV_LOG_SYSTEM_INIT
(integer)
SQLSRV_LOG_SYSTEM_OFF
(integer)
SQLSRV_LOG_SYSTEM_STMT
(integer)
SQLSRV_LOG_SYSTEM_UTIL
(integer)
SQLSRV_LOG_SEVERITY_ALL
(integer)
SQLSRV_LOG_SEVERITY_ERROR
(integer)
SQLSRV_LOG_SEVERITY_NOTICE
(integer)
SQLSRV_LOG_SEVERITY_WARNING
(integer)
SQLSRV_NULLABLE_YES
(integer)
SQLSRV_NULLABLE_NO
(integer)
SQLSRV_NULLABLE_UNKNOWN
(integer)
SQLSRV_PARAM_IN
(integer)
SQLSRV_PARAM_INOUT
(integer)
SQLSRV_PARAM_OUT
(integer)
SQLSRV_PHPTYPE_INT
(integer)
SQLSRV_PHPTYPE_DATETIME
(integer)
SQLSRV_PHPTYPE_FLOAT
(integer)
SQLSRV_PHPTYPE_STREAM
(integer)
SQLSRV_PHPTYPE_STRING
(integer)
SQLSRV_ENC_BINARY
(integer)
SQLSRV_ENC_CHAR
(integer)
UTF-8
(integer)
SQLSRV_SQLTYPE_BIGINT
(integer)
SQLSRV_SQLTYPE_BINARY
(integer)
SQLSRV_SQLTYPE_BIT
(integer)
SQLSRV_SQLTYPE_CHAR
(integer)
SQLSRV_SQLTYPE_DATE
(integer)
SQLSRV_SQLTYPE_DATETIME
(integer)
SQLSRV_SQLTYPE_DATETIME2
(integer)
SQLSRV_SQLTYPE_DATETIMEOFFSET
(integer)
SQLSRV_SQLTYPE_DECIMAL
(integer)
SQLSRV_SQLTYPE_FLOAT
(integer)
SQLSRV_SQLTYPE_IMAGE
(integer)
SQLSRV_SQLTYPE_INT
(integer)
SQLSRV_SQLTYPE_MONEY
(integer)
SQLSRV_SQLTYPE_NCHAR
(integer)
SQLSRV_SQLTYPE_NUMERIC
(integer)
SQLSRV_SQLTYPE_NVARCHAR
(integer)
SQLSRV_SQLTYPE_NVARCHAR('max')
(integer)
SQLSRV_SQLTYPE_NTEXT
(integer)
SQLSRV_SQLTYPE_REAL
(integer)
SQLSRV_SQLTYPE_SMALLDATETIME
(integer)
SQLSRV_SQLTYPE_SMALLINT
(integer)
SQLSRV_SQLTYPE_SMALLMONEY
(integer)
SQLSRV_SQLTYPE_TEXT
(integer)
SQLSRV_SQLTYPE_TIME
(integer)
SQLSRV_SQLTYPE_TIMESTAMP
(integer)
SQLSRV_SQLTYPE_TINYINT
(integer)
SQLSRV_SQLTYPE_UNIQUEIDENTIFIER
(integer)
SQLSRV_SQLTYPE_UDT
(integer)
SQLSRV_SQLTYPE_VARBINARY
(integer)
SQLSRV_SQLTYPE_VARBINARY('max')
(integer)
SQLSRV_SQLTYPE_VARCHAR
(integer)
SQLSRV_SQLTYPE_VARCHAR('max')
(integer)
SQLSRV_SQLTYPE_XML
(integer)
SQLSRV_TXN_READ_UNCOMMITTED
(integer)
SQLSRV_TXN_READ_COMMITTED
(integer)
SQLSRV_TXN_REPEATABLE_READ
(integer)
SQLSRV_TXN_SNAPSHOT
(integer)
SQLSRV_TXN_READ_SERIALIZABLE
(integer)
SQLSRV_CURSOR_FORWARD
(integer)
SQLSRV_CURSOR_STATIC
(integer)
SQLSRV_CURSOR_DYNAMIC
(integer)
SQLSRV_CURSOR_KEYSET
(integer)
SQLSRV_CURSOR_BUFFERED
(integer)
SQLSRV_SCROLL_NEXT
(integer)
SQLSRV_SCROLL_PRIOR
(integer)
SQLSRV_SCROLL_FIRST
(integer)
SQLSRV_SCROLL_LAST
(integer)
SQLSRV_SCROLL_ABSOLUTE
(integer)
SQLSRV_SCROLL_RELATIVE
(integer)
(No version information available, might only be in Git)
sqlsrv_begin_transaction — Begins a database transaction
$conn
) : boolThe transaction begun by sqlsrv_begin_transaction() includes all statements that were executed after the call to sqlsrv_begin_transaction() and before calls to sqlsrv_rollback() or sqlsrv_commit(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and commit/roll back transactions. For more information, see » SQLSRV Transactions.
Returns TRUE on success or FALSE on failure.
Example #1 sqlsrv_begin_transaction() example
The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>
The above example will output something similar to:
(No version information available, might only be in Git)
sqlsrv_cancel — Cancels a statement
$stmt
) : boolCancels a statement. Any results associated with the statement that have not been consumed are deleted. After sqlsrv_cancel() has been called, the specified statement can be re-executed if it was created with sqlsrv_prepare(). Calling sqlsrv_cancel() is not necessary if all the results associated with the statement have been consumed.
stmtThe statement resource to be cancelled.
Returns TRUE on success or FALSE on failure.
Example #1 sqlsrv_cancel() example
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Sales FROM Table_1";
$stmt = sqlsrv_prepare( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( sqlsrv_execute( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
$salesTotal = 0;
$count = 0;
while( ($row = sqlsrv_fetch_array( $stmt)) && $salesTotal <=100000)
{
$qty = $row[0];
$price = $row[1];
$salesTotal += ( $price * $qty);
$count++;
}
echo "$count sales accounted for the first $$salesTotal in revenue.<br />";
// Cancel the pending results. The statement can be reused.
sqlsrv_cancel( $stmt);
?>
The main difference between sqlsrv_cancel() and sqlsrv_free_stmt() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.
(No version information available, might only be in Git)
sqlsrv_client_info — Returns information about the client and specified connection
$conn
) : arrayReturns information about the client and specified connection
connThe connection about which information is returned.
Returns an associative array with keys described in the table below.
Returns FALSE otherwise.
| Key | Description |
|---|---|
| DriverDllName | SQLNCLI10.DLL |
| DriverODBCVer | ODBC version (xx.yy) |
| DriverVer | SQL Server Native Client DLL version (10.5.xxx) |
| ExtensionVer | php_sqlsrv.dll version (2.0.xxx.x) |
Example #1 sqlsrv_client_info() example
<?php
$serverName = "serverName\sqlexpress";
$connOptions = array("UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( $client_info = sqlsrv_client_info( $conn)) {
foreach( $client_info as $key => $value) {
echo $key.": ".$value."<br />";
}
} else {
echo "Error in retrieving client info.<br />";
}
?>
(No version information available, might only be in Git)
sqlsrv_close — Closes an open connection and releases resourses associated with the connection
$conn
) : boolCloses an open connection and releases resourses associated with the connection.
connThe connection to be closed.
Returns TRUE on success or FALSE on failure.
Example #1 sqlsrv_close() example
<?php
$serverName = "serverName\sqlexpres";
$connOptions = array("UID"=>"username", "PWD"=>"password", "Database"=>"dbname");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
//-------------------------------------
// Perform database operations here.
//-------------------------------------
// Close the connection.
sqlsrv_close( $conn );
?>
(No version information available, might only be in Git)
sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction()
$conn
) : boolCommits a transaction that was begun with sqlsrv_begin_transaction(). The connection is returned to auto-commit mode after sqlsrv_commit() is called. The transaction that is committed includes all statements that were executed after the call to sqlsrv_begin_transaction(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and commit/roll back transactions. For more information, see » SQLSRV Transactions.
connThe connection on which the transaction is to be committed.
Returns TRUE on success or FALSE on failure.
Example #1 sqlsrv_commit() example
The following example demonstrates how to use sqlsrv_commit() together with sqlsrv_begin_transaction() and sqlsrv_rollback().
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>
(No version information available, might only be in Git)
sqlsrv_configure — Changes the driver error handling and logging configurations
Changes the driver error handling and logging configurations.
settingThe name of the setting to set. The possible values are "WarningsReturnAsErrors", "LogSubsystems", and "LogSeverity".
valueThe value of the specified setting. The following table shows possible values:
| Setting | Options |
|---|---|
| WarningsReturnAsErrors | 1 (TRUE) or 0 (FALSE) |
| LogSubsystems | SQLSRV_LOG_SYSTEM_ALL (-1) SQLSRV_LOG_SYSTEM_CONN (2) SQLSRV_LOG_SYSTEM_INIT (1) SQLSRV_LOG_SYSTEM_OFF (0) SQLSRV_LOG_SYSTEM_STMT (4) SQLSRV_LOG_SYSTEM_UTIL (8) |
| LogSeverity | SQLSRV_LOG_SEVERITY_ALL (-1) SQLSRV_LOG_SEVERITY_ERROR (1) SQLSRV_LOG_SEVERITY_NOTICE (4) SQLSRV_LOG_SEVERITY_WARNING (2) |
Returns TRUE on success or FALSE on failure.
(No version information available, might only be in Git)
sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
$serverName
[, array $connectionInfo
] ) : resourceOpens a connection to a Microsoft SQL Server database. By default, the connection is attempted using Windows Authentication. To connect using SQL Server Authentication, include "UID" and "PWD" in the connection options array.
serverNameThe name of the server to which a connection is established. To connect to a specific instance, follow the server name with a backward slash and the instance name (e.g. serverName\sqlexpress).
connectionInfoAn associative array that specifies options for connecting to the server. If values for the UID and PWD keys are not specified, the connection will be attempted using Windows Authentication. For a complete list of supported keys, see » SQLSRV Connection Options.
A connection resource. If a connection cannot be successfully opened, FALSE is returned.
Example #1 Connect using Windows Authentication.
<?php
$serverName = "serverName\\sqlexpress"; //serverName\instanceName
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"dbName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
Example #2 Connect by specifying a user name and password.
<?php
$serverName = "serverName\\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
Example #3 Connect on a specified port.
<?php
$serverName = "serverName\\sqlexpress, 1542"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
By default, the sqlsrv_connect() uses connection pooling to
improve connection performance. To turn off connection pooling (i.e. force a
new connection on each call), set the "ConnectionPooling" option in the
$connectionOptions array to 0 (or FALSE). For more information, see
» SQLSRV Connection Pooling.
The SQLSRV extension does not have a dedicated function for changing which database is connected to. The target database is specified in the $connectionOptions array that is passed to sqlsrv_connect. To change the database on an open connection, execute the following query "USE dbName" (e.g. sqlsrv_query($conn, "USE dbName")).
(No version information available, might only be in Git)
sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed
Returns error and warning information about the last SQLSRV operation performed.
errorsOrWarningsDetermines whether error information, warning information, or both are returned. If this parameter is not supplied, both error information and warning information are returned. The following are the supported values for this parameter: SQLSRV_ERR_ALL, SQLSRV_ERR_ERRORS, SQLSRV_ERR_WARNINGS.
If errors and/or warnings occurred on the last sqlsrv operation, an array of
arrays containing error information is returned. If no errors and/or warnings
occurred on the last sqlsrv operation, NULL is returned. The following table
describes the structure of the returned arrays:
| Key | Description |
|---|---|
| SQLSTATE | For errors that originate from the ODBC driver, the SQLSTATE returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of IMSSP. For warnings that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of 01SSP. |
| code | For errors that originate from SQL Server, the native SQL Server error code. For errors that originate from the ODBC driver, the error code returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, the Microsoft Drivers for PHP for SQL Server error code. |
| message | A description of the error. |
Example #1 functionname() example
<?php
$serverName = "serverName/sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
/* Set up a query to select an invalid column name. */
$sql = "SELECT BadColumnName FROM Table_1";
/* Execution of the query will fail because of the bad column name. */
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
echo "code: ".$error[ 'code']."<br />";
echo "message: ".$error[ 'message']."<br />";
}
}
}
?>
By default, warnings generated on a call to any SQLSRV function are treated
as errors. This means that if a warning occurs on a call to a SQLSRV function,
the function returns FALSE. However, warnings that correspond to SQLSTATE
values 01000, 01001, 01003, and 01S02 are never treated as errors. For
information about changing this behavior, see sqlsrv_configure()
and the WarningsReturnAsErrors setting.
(No version information available, might only be in Git)
sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare()
$stmt
) : boolExecutes a statement prepared with sqlsrv_prepare(). This function is ideal for executing a prepared statement multiple times with different parameter values.
Returns TRUE on success or FALSE on failure.
Example #1 sqlsrv_execute() example
This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);
// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
?>
When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().
(No version information available, might only be in Git)
sqlsrv_fetch_array — Returns a row as an array
$stmt
[, int $fetchType
[, int $row
[, int $offset
]]] ) : arrayReturns the next available row of data as an associative array, a numeric array, or both (the default).
stmtA statement resource returned by sqlsrv_query or sqlsrv_prepare.
fetchType
A predefined constant specifying the type of array to return. Possible
values are SQLSRV_FETCH_ASSOC,
SQLSRV_FETCH_NUMERIC, and
SQLSRV_FETCH_BOTH (the default).
A fetch type of SQLSRV_FETCH_ASSOC should not be used when consuming a result set with multiple columns of the same name.
row
Specifies the row to access in a result set that uses a scrollable cursor.
Possible values are SQLSRV_SCROLL_NEXT,
SQLSRV_SCROLL_PRIOR, SQLSRV_SCROLL_FIRST,
SQLSRV_SCROLL_LAST, SQLSRV_SCROLL_ABSOLUTE and,
SQLSRV_SCROLL_RELATIVE (the default). When this parameter
is specified, the fetchType must be explicitly defined.
offset
Specifies the row to be accessed if the row parameter is set to
SQLSRV_SCROLL_ABSOLUTE or
SQLSRV_SCROLL_RELATIVE. Note that the first row in
a result set has index 0.
Returns an array on success, NULL if there are no more rows to return, and
FALSE if an error occurs.
Example #1 Retrieving an associative array.
<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['LastName'].", ".$row['FirstName']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
Example #2 Retrieving a numeric array.
<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
echo $row[0].", ".$row[1]."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
Not specifying the fetchType or explicitly using the
SQLSRV_FETCH_TYPE constant in the examples above will
return an array that has both associative and numeric keys.
If more than one column is returned with the same name, the last column will take precedence. To avoid field name collisions, use aliases.
If a column with no name is returned, the associative key for the array element will be an empty string ("").
(No version information available, might only be in Git)
sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object
$stmt
[, string $className
[, array $ctorParams
[, int $row
[, int $offset
]]]] ) : mixedRetrieves the next row of data in a result set as an instance of the specified class with properties that match the row field names and values that correspond to the row field values.
stmtA statement resource created by sqlsrv_query() or sqlsrv_execute().
classNameThe name of the class to instantiate. If no class name is specified, stdClass is instantiated.
ctorParamsValues passed to the constructor of the specified class. If the constructor of the specified class takes parameters, the ctorParams array must be supplied.
rowThe row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:
offset
Specifies the row to be accessed if the row parameter is set to
SQLSRV_SCROLL_ABSOLUTE or
SQLSRV_SCROLL_RELATIVE. Note that the first row in
a result set has index 0.
Returns an object on success, NULL if there are no more rows to return,
and FALSE if an error occurs or if the specified class does not exist.
Example #1 sqlsrv_fetch_object() example
The following example demonstrates how to retrieve a row as a stdClass object.
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT fName, lName FROM Table_1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Retrieve each row as an object.
// Because no class is specified, each row will be retrieved as a stdClass object.
// Property names correspond to field names.
while( $obj = sqlsrv_fetch_object( $stmt)) {
echo $obj->fName.", ".$obj->lName."<br />";
}
?>
If a class name is specified with the optional $className parameter and the class has properties whose names match the result set field names, the corresponding result set values are applied to the properties. If a result set field name does not match a class property, a property with the result set field name is added to the object and the result set value is applied to the property. The following rules apply when using the $className parameter:
FALSE and adds an error to the error collection.When consuming a result set that has multiple columns with the same name, it may be better to use sqlsrv_fetch_array() or the combination of sqlsrv_fetch() and sqlsrv_get_field().
(No version information available, might only be in Git)
sqlsrv_fetch — Makes the next row in a result set available for reading
Makes the next row in a result set available for reading. Use sqlsrv_get_field() to read the fields of the row.
stmtA statement resource created by executing sqlsrv_query() or sqlsrv_execute().
rowThe row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:
offset
Specifies the row to be accessed if the row parameter is set to
SQLSRV_SCROLL_ABSOLUTE or
SQLSRV_SCROLL_RELATIVE. Note that the first row in
a result set has index 0.
Returns TRUE if the next row of a result set was successfully retrieved,
FALSE if an error occurs, and NULL if there are no more rows in the result set.
Example #1 sqlsrv_fetch() example
The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Name, Comment
FROM Table_1
WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
// Get the row fields. Field indices start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";
$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>
(No version information available, might only be in Git)
sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query()
Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query(). sqlsrv_field_metadata() can be called on a statement before or after statement execution.
stmtThe statement resource for which metadata is returned.
Returns an array of arrays on success. Otherwise, FALSE is returned.
Each returned array is described by the following table:
| Key | Description |
|---|---|
| Name | The name of the field. |
| Type | The numeric value for the SQL type. |
| Size | The number of characters for fields of character type, the number of
bytes for fields of binary type, or NULL for other types. |
| Precision | The precision for types of variable precision, NULL for other types. |
| Scale | The scale for types of variable scale, NULL for other types. |
| Nullable | An enumeration indicating whether the column is nullable, not nullable, or if it is not known. |
Example #1 sqlsrv_field_metadata() example
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"AdventureWorks", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_prepare( $conn, $sql );
foreach( sqlsrv_field_metadata( $stmt ) as $fieldMetadata ) {
foreach( $fieldMetadata as $name => $value) {
echo "$name: $value<br />";
}
echo "<br />";
}
?>
(No version information available, might only be in Git)
sqlsrv_free_stmt — Frees all resources for the specified statement
$stmt
) : boolFrees all resources for the specified statement. The statement cannot be used after sqlsrv_free_stmt() has been called on it. If sqlsrv_free_stmt() is called on an in-progress statement that alters server state, statement execution is terminated and the statement is rolled back.
stmt
The statement for which resources are freed.
Note that NULL is a valid parameter value. This allows the function to be
called multiple times in a script.
Returns TRUE on success or FALSE on failure.
Example #1 sqlsrv_free_stmt() example
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
/*-------------------------------
Process query results here.
-------------------------------*/
/* Free the statement resources. */
sqlsrv_free_stmt( $stmt);
?>
The main difference between sqlsrv_free_stmt() and sqlsrv_cancel() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.
(No version information available, might only be in Git)
sqlsrv_get_config — Returns the value of the specified configuration setting
Returns the value of the specified configuration setting.
settingThe name of the setting for which the value is returned. For a list of configurable settings, see sqlsrv_configure().
Returns the value of the specified setting. If an invalid setting is specified,
FALSE is returned.
(No version information available, might only be in Git)
sqlsrv_get_field — Gets field data from the currently selected row
Gets field data from the currently selected row. Fields must be accessed in order. Field indices start at 0.
stmtA statement resource returned by sqlsrv_query() or sqlsrv_execute().
fieldIndexThe index of the field to be retrieved. Field indices start at 0. Fields must be accessed in order. i.e. If you access field index 1, then field index 0 will not be available.
getAsTypeThe PHP data type for the returned field data. If this parameter is not set, the field data will be returned as its default PHP data type. For information about default PHP data types, see » Default PHP Data Types in the Microsoft SQLSRV documentation.
Returns data from the specified field on success. Returns FALSE otherwise.
Example #1 sqlsrv_get_field() example
The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Name, Comment
FROM Table_1
WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
// Get the row fields. Field indices start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";
$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>
(No version information available, might only be in Git)
sqlsrv_has_rows — Indicates whether the specified statement has rows
$stmt
) : boolIndicates whether the specified statement has rows.
Returns TRUE if the specified statement has rows and FALSE if the statement
does not have rows or if an error occurred.
Example #1 sqlsrv_has_rows() example
<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" )
$conn = sqlsrv_connect( $server, $connectionInfo );
$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if ($stmt) {
$rows = sqlsrv_has_rows( $stmt );
if ($rows === true)
echo "There are rows. <br />";
else
echo "There are no rows. <br />";
}
?>
(No version information available, might only be in Git)
sqlsrv_next_result — Makes the next result of the specified statement active
Makes the next result of the specified statement active. Results include result sets, row counts, and output parameters.
stmtThe statement on which the next result is being called.
Returns TRUE if the next result was successfully retrieved, FALSE if an error
occurred, and NULL if there are no more results to retrieve.
Example #1 sqlsrv_next_result() example
The following example executes a batch query that inserts into a table and then selects from the table. This produces two results on the statement: one for the rows affected by the INSERT and one for the rows returned by the SELECT. To get to the rows returned by the SELECT, sqlsrv_next_result() must be called to move past the first result.
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array("Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$query = "INSERT INTO Table_1 (id, data) VALUES (?,?); SELECT * FROM TABLE_1;";
$params = array(1, "some data");
$stmt = sqlsrv_query($conn, $query, $params);
// Consume the first result (rows affected by INSERT) without calling sqlsrv_next_result.
echo "Rows affected: ".sqlsrv_rows_affected($stmt)."<br />";
// Move to the next result and display results.
$next_result = sqlsrv_next_result($stmt);
if( $next_result ) {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
echo $row['id'].": ".$row['data']."<br />";
}
} elseif( is_null($next_result)) {
echo "No more results.<br />";
} else {
die(print_r(sqlsrv_errors(), true));
}
?>
(No version information available, might only be in Git)
sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement
Retrieves the number of fields (columns) on a statement.
stmtThe statement for which the number of fields is returned. sqlsrv_num_fields() can be called on a statement before or after statement execution.
Returns the number of fields on success. Returns FALSE otherwise.
Example #1 sqlsrv_num_fields() example
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true));
}
$numFields = sqlsrv_num_fields( $stmt );
while( sqlsrv_fetch( $stmt )) {
// Iterate through the fields of each row.
for($i = 0; $i < $numFields; $i++) {
echo sqlsrv_get_field($stmt, $i)." ";
}
echo "<br />";
}
?>
(No version information available, might only be in Git)
sqlsrv_num_rows — Retrieves the number of rows in a result set
Retrieves the number of rows in a result set. This function requires that the statement resource be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.
stmtThe statement for which the row count is returned. The statement resource must be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.
Returns the number of rows retrieved on success and FALSE if an error occurred.
If a forward cursor (the default) or dynamic cursor is used, FALSE is returned.
Example #1 sqlsrv_num_rows() example
<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $server, $connectionInfo );
$sql = "SELECT * FROM Table_1";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $stmt );
if ($row_count === false)
echo "Error in retrieveing row count.";
else
echo $row_count;
?>
(No version information available, might only be in Git)
sqlsrv_prepare — Prepares a query for execution
Prepares a query for execution. This function is ideal for preparing a query that will be executed multiple times with different parameter values.
connA connection resource returned by sqlsrv_connect().
sqlThe string that defines the query to be prepared and executed.
paramsAn array specifying parameter information when executing a parameterized query. Array elements can be any of the following:
| Element | Description |
|---|---|
| $value | A literal value, a PHP variable, or a PHP by-reference variable. |
| $direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN. |
| $phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value. |
| $sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value. |
optionsAn array specifying query property options. The supported keys are described in the following table:
| Key | Values | Description |
|---|---|---|
| QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results. |
| SendStreamParamsAtExec | TRUE or FALSE (the default is TRUE) |
Configures the driver to send all stream data at execution (TRUE),
or to send stream data in chunks (FALSE). By default, the value is set to TRUE.
For more information, see sqlsrv_send_stream_data(). |
| Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation. |
Returns a statement resource on success and FALSE if an error occurred.
Example #1 sqlsrv_prepare() example
This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);
// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
?>
When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().
(No version information available, might only be in Git)
sqlsrv_query — Prepares and executes a query
Prepares and executes a query.
connA connection resource returned by sqlsrv_connect().
sqlThe string that defines the query to be prepared and executed.
paramsAn array specifying parameter information when executing a parameterized query. Array elements can be any of the following:
| Element | Description |
|---|---|
| $value | A literal value, a PHP variable, or a PHP by-reference variable. |
| $direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN. |
| $phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value. |
| $sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value. |
optionsAn array specifying query property options. The supported keys are described in the following table:
| Key | Values | Description |
|---|---|---|
| QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results. |
| SendStreamParamsAtExec | TRUE or FALSE (the default is TRUE) |
Configures the driver to send all stream data at execution (TRUE),
or to send stream data in chunks (FALSE). By default, the value is set
to TRUE. For more information, see sqlsrv_send_stream_data(). |
| Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation. |
Returns a statement resource on success and FALSE if an error occurred.
Example #1 sqlsrv_query() example
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
?>
For statements that you plan to execute only once, use sqlsrv_query(). If you intend to re-execute a statement with different parameter values, use the combination of sqlsrv_prepare() and sqlsrv_execute().
(No version information available, might only be in Git)
sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction()
$conn
) : boolRolls back a transaction that was begun with sqlsrv_begin_transaction() and returns the connection to auto-commit mode.
Returns TRUE on success or FALSE on failure.
Example #1 sqlsrv_rollback() example
The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>
(No version information available, might only be in Git)
sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
$stmt
) : intReturns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed. For information about the number of rows returned by a SELECT query, see sqlsrv_num_rows().
stmtThe executed statement resource for which the number of affected rows is returned.
Returns the number of rows affected by the last INSERT, UPDATE, or DELETE query.
If no rows were affected, 0 is returned. If the number of affected rows cannot
be determined, -1 is returned. If an error occurred, FALSE is returned.
Example #1 sqlsrv_rows_affected() example
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1 SET data = ? WHERE id = ?";
$params = array("updated data", 1);
$stmt = sqlsrv_query( $conn, $sql, $params);
$rows_affected = sqlsrv_rows_affected( $stmt);
if( $rows_affected === false) {
die( print_r( sqlsrv_errors(), true));
} elseif( $rows_affected == -1) {
echo "No information available.<br />";
} else {
echo $rows_affected." rows were updated.<br />";
}
?>
(No version information available, might only be in Git)
sqlsrv_send_stream_data — Sends data from parameter streams to the server
$stmt
) : boolSend data from parameter streams to the server. Up to 8 KB of data is sent with each call.
Returns TRUE if there is more data to send and FALSE if there is not.
Example #1 sqlsrv_send_stream_data() example
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1 SET data = ( ?) WHERE id = 100";
// Open parameter data as a stream and put it in the $params array.
$data = fopen( "data://text/plain,[ Lengthy content here. ]", "r");
$params = array( &$data);
// Prepare the statement. Use the $options array to turn off the
// default behavior, which is to send all stream data at the time of query
// execution.
$options = array("SendStreamParamsAtExec"=>0);
$stmt = sqlsrv_prepare( $conn, $sql, $params, $options);
sqlsrv_execute( $stmt);
// Send up to 8K of parameter data to the server
// with each call to sqlsrv_send_stream_data.
$i = 1;
while( sqlsrv_send_stream_data( $stmt)) {
$i++;
}
echo "$i calls were made.";
?>
(No version information available, might only be in Git)
sqlsrv_server_info — Returns information about the server
$conn
) : arrayReturns information about the server.
connThe connection resource that connects the client and the server.
Returns an array as described in the following table:
| CurrentDatabase | The connected-to database. |
|---|---|
| SQLServerVersion | The SQL Server version. |
| SQLServerName | The name of the server. |
Example #1 sqlsrv_server_info() example
<?php
$serverName = "serverName\sqlexpress";
$conn = sqlsrv_connect( $serverName);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$server_info = sqlsrv_server_info( $conn);
if( $server_info )
{
foreach( $server_info as $key => $value) {
echo $key.": ".$value."<br />";
}
} else {
die( print_r( sqlsrv_errors(), true));
}
?>
As of PHP 7.0.0, the sybase_ct extension has been removed.
No external libraries are needed to build this extension.
To enable Sybase-DB support configure PHP --with-sybase[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase. To enable Sybase-CT support configure PHP --with-sybase-ct[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase.
Note:
As of PHP 5.3.0, the Sybase extension has been superseded by the sybase_ct extension and is no longer maintained. To continue using sybase you must use the sybase_ct extension.
As of PHP 7.0.0, the sybase_ct extension has been removed.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| sybase.allow_persistent | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3. |
| sybase.max_persistent | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3. |
| sybase.max_links | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3. |
| sybase.interface_file | "/usr/sybase/interfaces" | PHP_INI_SYSTEM | |
| sybase.min_error_severity | "10" | PHP_INI_ALL | |
| sybase.min_message_severity | "10" | PHP_INI_ALL | |
| sybase.compatability_mode | "0" | PHP_INI_ALL | |
| magic_quotes_sybase | "0" | PHP_INI_ALL | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0. |
Here's a short explanation of the configuration directives.
sybase.allow_persistent
boolean
Whether to allow persistent Sybase connections.
sybase.max_persistent
integer
The maximum number of persistent Sybase connections per process. -1 means no limit.
sybase.max_links
integer
The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.
sybase.min_error_severity
integer
Minimum error severity to display.
sybase.min_message_severity
integer
Minimum message severity to display.
magic_quotes_sybase
boolean
If magic_quotes_sybase is on, a
single-quote is escaped with a single-quote instead of a
backslash if magic_quotes_gpc
or magic_quotes_runtime
are enabled.
This setting is also respected by addslashes() and
stripslashes().
Note:
Note that when
magic_quotes_sybaseis ON it completely overridesmagic_quotes_gpc. In this case even whenmagic_quotes_gpcis enabled neither double quotes, backslashes or NUL's will be escaped.
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
Here's a short explanation of the configuration directives.
sybct.login_timeout
integer
The maximum time in seconds to wait for a connection attempt to succeed before returning failure. Note that if max_execution_time has been exceeded when a connection attempt times out, your script will be terminated before it can take action on failure. The default is one minute.
sybct.timeout
integer
The maximum time in seconds to wait for a select_db or query operation to succeed before returning failure. Note that if max_execution_time has been exceeded when an operation times out, your script will be terminated before it can take action on failure. The default is no limit.
sybct.deadlock_retry_count
int
Allows you to define how often deadlocks are to be retried. The default is 0, value -1 means "forever".
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.
This extension has no resource types defined.
This extension has no constants defined.
(PHP 4, PHP 5)
sybase_affected_rows — Gets number of affected rows in last query
This function was REMOVED in PHP 7.0.0.
$link_identifier
] ) : intsybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier.
This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().
link_identifierIf the link identifier isn't specified, the last opened link is assumed.
Returns the number of affected rows, as an integer.
Example #1 Delete-Query
<?php
/* connect to database */
sybase_connect('SYBASE', '', '') or
die("Could not connect");
sybase_select_db("db");
sybase_query("DELETE FROM sometable WHERE id < 10");
printf("Records deleted: %d\n", sybase_affected_rows());
?>
The above example will output:
Records deleted: 10
(PHP 4, PHP 5)
sybase_close — Closes a Sybase connection
This function was REMOVED in PHP 7.0.0.
$link_identifier
] ) : bool
sybase_close() closes the link to a Sybase
database that's associated with the specified link
link_identifier.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
sybase_close() will not close persistent links generated by sybase_pconnect().
link_identifierIf the link identifier isn't specified, the last opened link is assumed.
Returns TRUE on success or FALSE on failure.
(PHP 4, PHP 5)
sybase_connect — Opens a Sybase server connection
This function was REMOVED in PHP 7.0.0.
$servername
[, string $username
[, string $password
[, string $charset
[, string $appname
[, bool $new = FALSE
]]]]]] ) : resourcesybase_connect() establishes a connection to a Sybase server.
In case a second call is made to sybase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling sybase_close().
servernameThe servername argument has to be a valid servername that is defined in the 'interfaces' file.
usernameSybase user name
password
Password associated with username.
charsetSpecifies the charset for the connection
appname
Specifies an appname for the Sybase connection.
This allow you to make separate connections in the same script to the
same database. This may come handy when you have started a transaction
in your current connection, and you need to be able to do a separate
query which cannot be performed inside this transaction.
newWhether to open a new connection or use the existing one.
Returns a positive Sybase link identifier on success, or FALSE on
failure.
| Version | Description |
|---|---|
| 5.3.0 |
The new parameter was added.
|
Example #1 sybase_connect() example
<?php
$link = sybase_connect('SYBASE', '', '')
or die("Could not connect !");
echo "Connected successfully";
sybase_close($link);
?>
(PHP 4, PHP 5)
sybase_data_seek — Moves internal row pointer
This function was REMOVED in PHP 7.0.0.
$result_identifier
, int $row_number
) : boolsybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specified row number. The next call to sybase_fetch_row() would return that row.
result_identifier
row_number
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.3.0, PHP 5)
sybase_deadlock_retry_count — Sets the deadlock retry count
This function was REMOVED in PHP 7.0.0.
$retry_count
) : voidUsing sybase_deadlock_retry_count(), the number of retries can be defined in cases of deadlocks. By default, every deadlock is retried an infinite number of times or until the process is killed by Sybase, the executing script is killed (for instance, by set_time_limit()) or the query succeeds.
retry_count
| -1 | Retry forever (default) |
| 0 | Do not retry |
| n | Retry n times |
No value is returned.
Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.
(PHP 4, PHP 5)
sybase_fetch_array — Fetch row as array
This function was REMOVED in PHP 7.0.0.
$result
) : arraysybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.
result
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
Note:
When selecting fields with identical names (for instance, in a join), the associative indices will have a sequential number prepended. See the example for details.
Example #1 Identical fieldnames
<?php
$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_query('SELECT * FROM p, a WHERE p.person_id= a.person_id');
var_dump(sybase_fetch_array($q));
sybase_close($dbh);
?>
The above example would produce the following output (assuming the two tables only have each one column called "person_id"):
array(4) {
[0]=>
int(1)
["person_id"]=>
int(1)
[1]=>
int(1)
["person_id1"]=>
int(1)
}
(PHP 4 >= 4.3.0, PHP 5)
sybase_fetch_assoc — Fetch a result row as an associative array
This function was REMOVED in PHP 7.0.0.
$result
) : arraysybase_fetch_assoc() is a version of sybase_fetch_row() that uses column names instead of integers for indices in the result array. Columns from different tables with the same names are returned as name, name1, name2, ..., nameN.
An important thing to note is that using sybase_fetch_assoc() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.
result
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows.
Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.
(PHP 4, PHP 5)
sybase_fetch_field — Get field information from a result
This function was REMOVED in PHP 7.0.0.
$result
[, int $field_offset = -1
] ) : objectsybase_fetch_field() can be used in order to obtain information about fields in a certain query result.
result
field_offsetIf the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.
Returns an object containing field information.
The properties of the object are:
(PHP 4, PHP 5)
sybase_fetch_object — Fetch a row as an object
This function was REMOVED in PHP 7.0.0.
sybase_fetch_object() is similar to sybase_fetch_assoc(), with one difference - an object is returned, instead of an array.
Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).
result
object
Use the second object to specify the type of object
you want to return. If this parameter is omitted, the object will be of
type stdClass.
Returns an object with properties that correspond to the fetched row, or
FALSE if there are no more rows.
Example #1 sybase_fetch_object() return as Foo
<?php
class Foo {
var $foo, $bar, $baz;
}
// {...]
$qrh= sybase_query('SELECT foo, bar, baz FROM example');
$foo= sybase_fetch_object($qrh, 'Foo');
$bar= sybase_fetch_object($qrh, new Foo());
// {...]
?>
(PHP 4, PHP 5)
sybase_fetch_row — Get a result row as an enumerated array
This function was REMOVED in PHP 7.0.0.
$result
) : arraysybase_fetch_row() fetches one row of data from the result associated with the specified result identifier.
Subsequent call to sybase_fetch_row() would
return the next row in the result set, or FALSE if there are no
more rows.
result
Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows. Each result column is stored in an array offset,
starting at offset 0.
| PHP | Sybase |
|---|---|
| string | VARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME |
| int | NUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT, TINYINT, SMALLINT |
| float | NUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY |
NULL |
NULL |
(PHP 4, PHP 5)
sybase_field_seek — Sets field offset
This function was REMOVED in PHP 7.0.0.
$result
, int $field_offset
) : boolSeeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.
result
field_offset
Returns TRUE on success or FALSE on failure.
(PHP 4, PHP 5)
sybase_free_result — Frees result memory
This function was REMOVED in PHP 7.0.0.
$result
) : boolsybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.
result
Returns TRUE on success or FALSE on failure.
(PHP 4, PHP 5)
sybase_get_last_message — Returns the last message from the server
This function was REMOVED in PHP 7.0.0.
sybase_get_last_message() returns the last message reported by the server.
Returns the message as a string.
(PHP 4, PHP 5)
sybase_min_client_severity — Sets minimum client severity
This function was REMOVED in PHP 7.0.0.
$severity
) : voidsybase_min_client_severity() sets the minimum client severity level.
severity
No value is returned.
Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.
(PHP 4, PHP 5)
sybase_min_error_severity — Sets minimum error severity
This function was REMOVED in PHP 7.0.0.
$severity
) : voidsybase_min_error_severity() sets the minimum error severity level.
severity
No value is returned.
Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.
(PHP 4, PHP 5)
sybase_min_message_severity — Sets minimum message severity
This function was REMOVED in PHP 7.0.0.
$severity
) : voidsybase_min_message_severity() sets the minimum message severity level.
severity
No value is returned.
Note: This function is only available when using the DB library interface to Sybase, and not with the CT library.
(PHP 4, PHP 5)
sybase_min_server_severity — Sets minimum server severity
This function was REMOVED in PHP 7.0.0.
$severity
) : voidsybase_min_server_severity() sets the minimum server severity level.
severity
No value is returned.
Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.
(PHP 4, PHP 5)
sybase_num_fields — Gets the number of fields in a result set
This function was REMOVED in PHP 7.0.0.
$result
) : intsybase_num_fields() returns the number of fields in a result set.
result
Returns the number of fields as an integer.
(PHP 4, PHP 5)
sybase_num_rows — Get number of rows in a result set
This function was REMOVED in PHP 7.0.0.
$result
) : intsybase_num_rows() returns the number of rows in a result set.
result
Returns the number of rows as an integer.
(PHP 4, PHP 5)
sybase_pconnect — Open persistent Sybase connection
This function was REMOVED in PHP 7.0.0.
$servername
[, string $username
[, string $password
[, string $charset
[, string $appname
]]]]] ) : resourcesybase_pconnect() acts very much like sybase_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()).
This type of links is therefore called 'persistent'.
servernameThe servername argument has to be a valid servername that is defined in the 'interfaces' file.
usernameSybase user name
password
Password associated with username.
charsetSpecifies the charset for the connection
appname
Specifies an appname for the Sybase connection.
This allow you to make separate connections in the same script to the
same database. This may come handy when you have started a transaction
in your current connection, and you need to be able to do a separate
query which cannot be performed inside this transaction.
Returns a positive Sybase persistent link identifier on success, or
FALSE on error.
(PHP 4, PHP 5)
sybase_query — Sends a Sybase query
This function was REMOVED in PHP 7.0.0.
sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier.
query
link_identifierIf the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.
Returns a positive Sybase result identifier on success, FALSE on error,
or TRUE if the query was successful but didn't return any columns.
(PHP 4, PHP 5)
sybase_result — Get result data
This function was REMOVED in PHP 7.0.0.
Returns the contents of the cell at the row and offset in the specified Sybase result set.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Recommended high-performance alternatives: sybase_fetch_row(), sybase_fetch_array() and sybase_fetch_object().
result
row
fieldThe field argument can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.
sybase_result() returns the contents of one cell from a Sybase result set.
(PHP 4, PHP 5)
sybase_select_db — Selects a Sybase database
This function was REMOVED in PHP 7.0.0.
$database_name
[, resource $link_identifier
] ) : boolsybase_select_db() sets the current active database on the server that's associated with the specified link identifier.
Every subsequent call to sybase_query() will be made on the active database.
database_name
link_identifierIf no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.3.0, PHP 5)
sybase_set_message_handler — Sets the handler called when a server message is raised
This function was REMOVED in PHP 7.0.0.
sybase_set_message_handler() sets a user function to handle messages generated by the server. You may specify the name of a global function, or use an array to specify an object reference and a method name.
handler
The handler expects five arguments in the following order: message
number, severity, state, line number and description. The first four
are integers. The last is a string. If the function returns FALSE,
PHP generates an ordinary error message.
link_identifierIf the link identifier isn't specified, the last opened link is assumed.
Returns TRUE on success or FALSE on failure.
Example #1 sybase_set_message_handler() callback function
<?php
function msg_handler($msgnumber, $severity, $state, $line, $text)
{
var_dump($msgnumber, $severity, $state, $line, $text);
}
sybase_set_message_handler('msg_handler');
?>
Example #2 sybase_set_message_handler() callback to a class
<?php
class Sybase {
function handler($msgnumber, $severity, $state, $line, $text)
{
var_dump($msgnumber, $severity, $state, $line, $text);
}
}
$sybase= new Sybase();
sybase_set_message_handler(array($sybase, 'handler'));
?>
Example #3 sybase_set_message_handler() unhandled messages
<?php
// Return FALSE from this function to indicate you can't handle
// this. The error is printed out as a warning, the way you're used
// to it if there is no handler installed.
function msg_handler($msgnumber, $severity, $state, $line, $text)
{
if (257 == $msgnumber) {
return false;
}
var_dump($msgnumber, $severity, $state, $line, $text);
}
sybase_set_message_handler('msg_handler');
?>
Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.
(PHP 4 >= 4.3.0, PHP 5)
sybase_unbuffered_query — Send a Sybase query and do not block
This function was REMOVED in PHP 7.0.0.
$query
, resource $link_identifier
[, bool $store_result
] ) : resourcesybase_unbuffered_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.
Unlike sybase_query(), sybase_unbuffered_query() reads only the first row of the result set. sybase_fetch_array() and similar function read more rows as needed. sybase_data_seek() reads up to the target row. The behavior may produce better performance for large result sets.
sybase_num_rows() will only return the correct number of rows if all result sets have been read. To Sybase, the number of rows is not known and is therefore computed by the client implementation.
Note:
If you don't read all of the resultsets prior to executing the next query, PHP will raise a warning and cancel all of the pending results. To get rid of this, use sybase_free_result() which will cancel pending results of an unbuffered query.
query
link_identifier
store_result
The optional store_result can be FALSE to
indicate the resultsets shouldn't be fetched into memory, thus
minimizing memory usage which is particularly interesting with very
large resultsets.
Returns a positive Sybase result identifier on success, or FALSE on
error.
Example #1 sybase_unbuffered_query() example
<?php
$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_unbuffered_query('select firstname, lastname from huge_table', $dbh, false);
sybase_data_seek($q, 10000);
$i = 0;
while ($row = sybase_fetch_row($q)) {
echo $row[0], ' ', $row[1], '<br />';
if ($i++ > 40000) {
break;
}
}
sybase_free_result($q);
sybase_close($dbh);
?>
Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.
tokyo_tyrant extension provides a wrapper for Tokyo Tyrant client libraries. The extension contains the normal key-value API and the table API.
"Tokyo Tyrant is a package of network interface to the DBM called Tokyo Cabinet. Though the DBM has high performance, you might bother in case that multiple processes share the same database, or remote processes access the database. Thus, Tokyo Tyrant is provided for concurrent and remote connections to Tokyo Cabinet. It is composed of the server process managing a database and its access library for client applications." --Tokyo Tyrant documentation
Tokyo Tyrant is written by Mikio Hirabayashi and is licensed under GNU Lesser General Public License.
Before using this extension Tokyo Cabinet and Tokyo Tyrant must be installed.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/tokyo_tyrant
--with-tokyo-tyrant[=DIR] DIR is the prefix to the Tokyo Tyrant installation--with-tokyo-cabinet-dir[=DIR] DIR is the prefix to the Tokyo Cabinet installation--disable-tokyo-tyrant-session Disable Tokyo Tyrant session handler support
The extension can be enabled by adding extension=tokyo_tyrant.so to the INI-configuration
ttserver -port 2000 -ext /path/to/expire.lua -extpc expire 30.0 '/tmp/sessions.tct#idx=ts:dec'
Note: expire.lua is included in the tokyo_tyrant extension source distribution
Note: It is important to make sure that tokyo_tyrant.session_salt matches on all servers.
The session handler creates a session id like the following: 8b0e27a823fa4a6cf7246945b82c1d51-a5eadbbed1f2075952900628456bfd6830541629-0-5460
The parts from left to right:
Session id - Generated session idChecksum - Checksum of session salt, session id, node id and primary keyNode id - The id of the node where the session maps toPrimary key - The primary key of the row where the session is storedThe checksum contains SHA1 sum of the node id, primary key, session id and the salt which is known only on the server side. This allows quick mapping of session id to node and primary key since there is no need to do an additional search. During session id regeneration only the parts 1 and 2 change but the mapping to the node and primary key stays constant.
In case some of the nodes fail tokyo_tyrant.allow_failover, tokyo_tyrant.fail_threshold and tokyo_tyrant.health_check_divisor INI-settings control the behavior during failover. If failover is allowed the session handler will map the session to a healthy node and creates a new empty session.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| tokyo_tyrant.default_timeout | 2.0 | PHP_INI_ALL | |
| tokyo_tyrant.session_salt | NULL |
PHP_INI_ALL | |
| tokyo_tyrant.key_prefix | NULL |
PHP_INI_ALL | |
| tokyo_tyrant.allow_failover | 1 | PHP_INI_ALL | |
| tokyo_tyrant.fail_threshold | 5 | PHP_INI_ALL | |
| tokyo_tyrant.health_check_divisor | 1000 | PHP_INI_ALL | |
| tokyo_tyrant.php_expiration | 0 | PHP_INI_ALL |
Here's a short explanation of the configuration directives.
tokyo_tyrant.default_timeout
integer
Default timeout when connecting to databases
tokyo_tyrant.session_salt
string
The secret that is used to salt session id
tokyo_tyrant.key_prefix
string
Prefix all keys with this string. The prefix is transparent to the developer but helps making sure that keys won't collide if multiple applications are using the same database.
tokyo_tyrant.allow_failover
integer
Whether to allow session failover in case a server dies.
tokyo_tyrant.fail_threshold
integer
How many read/write or connection failures is allowed before server is marked as failed.
tokyo_tyrant.health_check_divisor
integer
Defines the divisor for the health check probability. If there are failed servers and the probability matches, the servers are health checked and in case the server seems healthy, it will be added back to the pool.
tokyo_tyrant.php_expiration
integer
Whether to use built in session expiration mechanism or delegate the expiration to a lua-script on the server-side.
This extension has no resource types defined.
Basic usage
Example #1 Putting and getting a key-value pair
<?php
$tt = new TokyoTyrant("localhost");
$tt->put("key", "value");
echo $tt->get("key");
?>
The above example will output:
value
(PECL tokyo_tyrant >= 0.1.0)
The main Tokyo Tyrant class
$host
[, int $port = TokyoTyrant::RDBDEF_PORT
[, array $options
]] ) : TokyoTyrantTokyoTyrant::RDBDEF_PORTThe default port of the Tokyo Tyrant database
TokyoTyrant::RDBQC_STREQstring is equal to
TokyoTyrant::RDBQC_STRINCstring is included in
TokyoTyrant::RDBQC_STRBWstring begins with
TokyoTyrant::RDBQC_STREWstring ends with
TokyoTyrant::RDBQC_STRANDstring includes all tokens in
TokyoTyrant::RDBQC_STRORstring includes at least one token in
TokyoTyrant::RDBQC_STROREQstring is equal to at least one token in
TokyoTyrant::RDBQC_STRRXstring matches regular expressions of
TokyoTyrant::RDBQC_NUMEQnumber is equal to
TokyoTyrant::RDBQC_NUMGTnumber is greater than
TokyoTyrant::RDBQC_NUMGEnumber is greater than or equal to
TokyoTyrant::RDBQC_NUMLTnumber is less than
TokyoTyrant::RDBQC_NUMLEnumber is less than or equal to
TokyoTyrant::RDBQC_NUMBTnumber is between two tokens of
TokyoTyrant::RDBQC_NUMOREQnumber is equal to at least one token in
TokyoTyrant::RDBQC_NEGATEnegation flag
TokyoTyrant::RDBQC_NOIDXno index flag
TokyoTyrant::RDBQO_STRASCstring ascending
TokyoTyrant::RDBQO_STRDESCstring descending
TokyoTyrant::RDBQO_NUMASCnumber ascending
TokyoTyrant::RDBQO_NUMDESCnumber descending
TokyoTyrant::RDBIT_LEXICALlexical string
TokyoTyrant::RDBIT_DECIMALdecimal string
TokyoTyrant::RDBIT_TOKENtoken inverted index (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBIT_QGRAMQGRAM inverted index (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBIT_OPToptimize
TokyoTyrant::RDBIT_VOIDvoid
TokyoTyrant::RDBIT_KEEPkeep existing index
TokyoTyrant::RDBQCFTS_PHfull-text search with the phrase of (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBQCFTS_ANDfull-text search with all tokens in (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBQCFTS_ORfull-text search with at least one token in (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBQCFTS_EXfull-text search with the compound expression of (Tokyo Tyrant >= 1.1.29)
TokyoTyrant::RDBQCFTS_ANDMetasearch union between records (Tokyo Tyrant >= 1.1.33)
TokyoTyrant::RDBQCFTS_ORMetasearch intersection between records (Tokyo Tyrant >= 1.1.33)
TokyoTyrant::RDBQCFTS_EXMetasearch difference between records (Tokyo Tyrant >= 1.1.33)
TokyoTyrant::RDBT_RECONWhether to reconnect on connection failure. It is recommended to have this parameter on for persistent connections
TokyoTyrant::RDBXOLCK_RECrecord locking
TokyoTyrant::RDBXOLCK_GLBglobal locking
TokyoTyrant::RDBREC_INTrecord type int
TokyoTyrant::RDBREC_DBLrecord type float (double)
TokyoTyrant::TTE_SUCCESSsuccess
TokyoTyrant::TTE_INVALIDinvalid operation
TokyoTyrant::TTE_NOHOSThost not found
TokyoTyrant::TTE_REFUSEDconnection refused
TokyoTyrant::TTE_SENDsend error
TokyoTyrant::TTE_RECVrecv error
TokyoTyrant::TTE_KEEPrecord exist
TokyoTyrant::TTE_NORECno record found
TokyoTyrant::TTE_MISCmiscellaneous error
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::add — Adds to a numeric key
Adds to an int or double value. This increments the value by the given amount and returns the new value. If the key does not exist a new key is created with initial value of the increment parameter.
keyThe string key
incrementThe amount to increment
type
TokyoTyrant::RDBREC_INT or TokyoTyrant::RDBREC_DBL constant.
If this parameter is omitted the type is guessed from the increment
parameters type.
Returns the new value on success
Example #1 TokyoTyrant::add() example
<?php
$tt = new TokyoTyrant("localhost", TokyoTyrant::RDBDEF_PORT);
/* Adds integer 3 to key and creates a new key */
$tt->add("test", 3);
/* String value is converted to double */
echo $tt->add("test", "3.5", TokyoTyrant::RDBREC_DBL);
?>
The above example will output something similar to:
6.5
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::connect — Connect to a database
$host
[, int $port = TokyoTyrant::RDBDEF_PORT
[, array $options
]] ) : TokyoTyrantConnects to a remote database
hostThe hostname
portThe port. Default: 1978
options
Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)
This method returns the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::connect() example
<?php
$tt = new TokyoTyrant();
$tt->connect("localhost", TokyoTyrant::RDBDEF_PORT)->put("test", "value");
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::connectUri — Connects to a database
Connects to a database using an uri
uri
An URI to the database. For example tcp://localhost:1979/
This method returns the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::connectUri() example
<?php
$tt = new TokyoTyrant();
$tt->connectUri("tcp://localhost:1978/")->put("test", "hi");
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::__construct — Construct a new TokyoTyrant object
$host
[, int $port = TokyoTyrant::RDBDEF_PORT
[, array $options
]]] )Constructs a new TokyoTyrant object and optionally connects to the database
host
The hostname. Default: NULL
portport number. Default: 1978
options
Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)
Throws TokyoTyrantException if connection to database fails
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::copy — Copies the database
Makes a copy of the current database
pathPath to where to copy the database. The user running the remote database must have a write access to the directory.
This method returns the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::copy() example
<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->copy("/tmp/foobar.tct");
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::ext — Execute a remote script
$name
, int $options
, string $key
, string $value
) : stringExecutes a remote script extension.
nameName of the function to execute
options
Either TokyoTyrant::RDBXO_LCKREC for record locking and
TokyoTyrant::RDBXO_LCKGLB for global locking.
keyThe key to pass to the function
valueThe value to pass to the function
Returns the result of the script function
Example #1 TokyoTyrant::ext() example
<?php
$tt = new TokyoTyrant("localhost", 1978);
echo $tt->ext("somefunc", TokyoTyrant::RDBXO_LCKREC, "some_key", "some_value");
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::fwmKeys — Returns the forward matching keys
$prefix
, int $max_recs
) : arrayReturns the forward matching keys from the database
prefixPrefix of the keys
max_recsMaximum records to return
Returns an array of matching keys. The values are not returned
Example #1 TokyoTyrant::fwmKeys() example
<?php
$tt = new TokyoTyrant("localhost");
/* Create 20 macthing keys */
for ($i = 0; $i < 20; $i++) {
$tt->put("key_" . $i, "value_" . $i);
}
/* Create 20 non-macthing keys */
for ($i = 0; $i < 20; $i++) {
$tt->put("something_" . $i, "data_" . $i);
}
/* Get five matching keys */
var_dump($tt->fwmKeys("key_", 5));
?>
The above example will output something similar to:
array(5) {
[0]=>
string(5) "key_5"
[1]=>
string(6) "key_14"
[2]=>
string(5) "key_6"
[3]=>
string(6) "key_15"
[4]=>
string(5) "key_7"
}
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::get — The get purpose
This method is used to return a value or multiple values. This method accepts a string or an array as a value.
Returns a string or an array based on the given parameters. Throws a TokyoTyrantException on error. If string is passed null is returned if the key is not found. In case an array is given as an parameter only existing keys will be returned. It is not an error to pass a key that does not exist.
Example #1 TokyoTyrant::get() example
<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->put("key1", "value1");
$tt->put("key2", "value2");
var_dump($tt->get(array("key1", "key2")));
var_dump($tt->get("key1"));
?>
The above example will output:
array(2) {
["key1"]=>
string(6) "value1"
["key2"]=>
string(6) "value2"
}
string(6) "value1"
(No version information available, might only be in Git)
TokyoTyrant::getIterator — Get an iterator
Gets an iterator for iterating all keys / values in the database.
This function has no parameters.
This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::getIterator() example
<?php
$tt = new TokyoTyrant("localhost");
$it = $tt->getIterator();
foreach ($it as $k => $v) {
}
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::num — Number of records in the database
Returns the number of records in the database
This function has no parameters.
Returns number of records in the database
Example #1 TokyoTyrant::num() example
<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");
/* Echo the number of records */
echo $tt->num();
?>
The above example will output something similar to:
1234
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::out — Removes records
Removes a record or multiple records. This method accepts a string for a single key or an array of keys for multiple records.
This method returns the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::out() example
<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");
$tt->put("test1", "value1");
$tt->put("test2", "value2");
$tt->out(array("test1", "test2"));
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::put — Puts values
Puts a key-value pair into the database or multiple key-value pairs. If keys is
string then the second parameter value defines the value.
The second parameter is mandatory if keys is a string. If the key exists the value
will be replaced with new value.
keysA string key or an array of key-value pairs
valueThe value in case a string key is used
This method returns a reference to the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::put() example
<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");
/* Put single key-value pair */
$tt->put("key", "value");
/* Put key-value pairs, new value overwrites the old */
$tt->put(array("key1" => "value1", "key" => "value2"));
/* Get back one key */
echo $tt->get("key");
?>
The above example will output:
value2
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::putCat — Concatenates to a record
Appends a value into existing key or multiple values if keys is an array.
The second parameter is mandatory if keys is a string. If the record does
not exist a new record is created.
This method returns a reference to the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::putCat() example
<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");
/* Create a new key */
$tt->put("key", "value");
/* Concatenate single key-value pair */
$tt->putCat("key", " has more data");
/* Echo the key */
echo $tt->get("key");
?>
The above example will output:
value has more data
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::putKeep — Puts a record
Puts a key-value pair into the database or multiple key-value pairs. If keys is
string then the second parameter value defines the value.
The second parameter is mandatory if keys is a string. If the key already
exists this method throws an exception indicating that the records exists.
This method returns a reference to the current object and throws TokyoTyrantException on failure.
Example #1 tokyotyrant::putKeep() example
<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");
/* Create a new key */
$tt->put("key", "value");
try {
$tt->putKeep("key", "new value");
} catch (TokyoTyrantException $e) {
if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
echo "Existing record! Not modified\n";
} else {
echo "Error: " , $e->getMessage() , "\n";
}
}
echo $tt->get("key");
?>
The above example will output:
Existing record! Not modified value
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::putNr — Puts value
Puts a key-value pair into the database or multiple key-value pairs. If keys is
string then the second parameter value defines the value.
The second parameter is mandatory if keys is a string. This method does not wait
for the response from the server.
keysA string key or an array of key-value pairs
valueThe value in case a string key is used
This method returns a reference to the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::putNr() example
<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");
/* Put single key-value pair */
$tt->putNr("key", "value");
/* Put key-value pairs */
$tt->putNr(array("key1" => "value1", "key2" => "value2"));
/* Get back one key */
echo $tt->get("key1");
?>
The above example will output:
value1
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::putShl — Concatenates to a record
Concatenate to a record and shift to left.
keyA string key
valueThe value to concatenate
widthThe width of the record
This method returns a reference to the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::putShl() example
<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");
/* Create a new key */
$tt->put("key", "just a long piece of data");
/* Concatenate and shift to left */
$tt->putShl("key", " and string", 15);
/* Echo the key */
echo $tt->get("key");
?>
The above example will output:
data and string
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::restore — Restore the database
$log_dir
, int $timestamp
[, bool $check_consistency = TRUE
] ) : mixedRestore the database from the update log.
This method is not supported on 32bit platforms.
log_dirDirectory where the log is
timestampBeginning timestamp with microseconds
check_consistency
Whether to check consistency: Default: TRUE
This method returns the current object and throws TokyoTyrantException on failure.
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::setMaster — Set the replication master
$host
, int $port
, int $timestamp
[, bool $check_consistency = TRUE
] ) : mixedSets the replication master of the database
This method is not supported on 32bit platforms.
host
Hostname of the replication master. If NULL the replication is disabled.
portPort of the replication master
timestampBeginning timestamp with microseconds
check_consistencyWhether to check consistency.
This method returns the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::setMaster() example
<?php
/* Connect to a database */
$tt = new TokyoTyrant("tokyotyrant.example.com");
/* Disable the replication */
$tt->setMaster(NULL, 0, 0);
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::size — Returns the size of the value
$key
) : intReturns the size of a value by key
keyThe key of which size to fetch
Returns the size of the key or throw TokyoTyrantException on error
Example #1 TokyoTyrant::size() example
<?php
$tt = new TokyoTyrant("localhost");
$tt->put("test_key", "12345");
echo $tt->size("test_key");
?>
The above example will output:
5
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::stat — Get statistics
Returns statistics of the remote database
This function has no parameters.
Returns an array of key value pairs describing the statistics
Example #1 TokyoTyrant::stat() example
<?php
$tt = new TokyoTyrant("localhost");
var_dump($tt->stat());
?>
The above example will output something similar to:
array(19) {
["version"]=>
string(6) "1.1.28"
["libver"]=>
string(3) "311"
["protver"]=>
string(4) "0.91"
["os"]=>
string(5) "Linux"
["time"]=>
string(17) "1247358357.665630"
["pid"]=>
string(5) "14348"
["sid"]=>
string(8) "59025947"
["type"]=>
string(9) "on-memory"
["path"]=>
string(1) "*"
["rnum"]=>
string(1) "4"
["size"]=>
string(6) "262856"
["bigend"]=>
string(1) "0"
["fd"]=>
string(1) "5"
["loadavg"]=>
string(8) "0.000000"
["memsize"]=>
string(8) "77328384"
["memrss"]=>
string(7) "1183744"
["ru_real"]=>
string(13) "162776.042152"
["ru_user"]=>
string(8) "0.476029"
["ru_sys"]=>
string(8) "8.652540"
}
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::sync — Synchronize the database
Synchronizes the database on to the physical device
This function has no parameters.
This method returns the current object and throws TokyoTyrantException on failure.
(PECL tokyo_tyrant >= 0.2.0)
TokyoTyrant::tune — Tunes connection values
$timeout
[, int $options = TokyoTyrant::RDBT_RECON
] ) : TokyoTyrantTunes database connection options.
timeoutThe objects timeout value (default: 5.0)
options
Bitmask of options to tune. This can be either 0 or TokyoTyrant::RDBT_RECON.
It is recommended not to change the second parameter.
This method returns a reference to the current object and throws TokyoTyrantException on failure.
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrant::vanish — Empties the database
This function has no parameters.
This method returns the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrant::vanish() example
<?php
$tt = new TokyoTyrant("localhost");
$tt->vanish();
?>
(PECL tokyo_tyrant >= 0.1.0)
Provides an API to the table databases. A table database can be create using the following
command: ttserver -port 1979 /tmp/tt_table.tct. In Tokyo Tyrant the table
API is a schemaless database which can store arbitrary amount of key-value pairs under a single
primary key.
$host
[, int $port = TokyoTyrant::RDBDEF_PORT
[, array $options
]] ) : TokyoTyrant$host
[, int $port = TokyoTyrant::RDBDEF_PORT
[, array $options
]]] )$log_dir
, int $timestamp
[, bool $check_consistency = TRUE
] ) : mixed$host
, int $port
, int $timestamp
[, bool $check_consistency = TRUE
] ) : mixed$timeout
[, int $options = TokyoTyrant::RDBT_RECON
] ) : TokyoTyrant(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::add — Adds a record
This method is not supported with table databases.
keyThe string key
incrementThe amount to increment
type
TokyoTyrant::RDB_RECINT or TokyoTyrant::RDB_RECDBL constant.
If this parameter is omitted the type is guessed from the increment
parameters type.
This method throws an TokyoTyrantException if used through this class.
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::genUid — Generate unique id
Generates an unique id inside the table database. In table databases rows are referenced using a numeric primary key.
This function has no parameters.
Returns an unique id or throws TokyoTyrantException on error
Example #1 TokyoTyrantTable::genUid() example
<?php
$tt = new TokyoTyrantTable("localhost", 1122);
echo $tt->genUid();
?>
The above example will output something similar to:
4
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::get — Get a row
Gets a row from table database. keys is a single integer for
the primary key of the row or an array of integers for multiple rows.
keysThe primary key, can be a string or an integer
Returns the row as an array
Example #1 TokyoTyrantTable::get() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));
/* Get the row back */
var_dump($tt->get($index));
?>
The above example will output:
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
Note:
Starting from version 0.3.0 this method accepts array as parameter. Please note that multi-get on tables is not binary-safe.
(No version information available, might only be in Git)
TokyoTyrantTable::getIterator — Get an iterator
Gets an iterator for iterating all keys / values in the database.
This function has no parameters.
This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrantTable::getIterator() example
<?php
$tt = new TokyoTyrantTable("localhost");
$it = $tt->getIterator();
foreach ($it as $k => $v) {
var_dump($k, $v);
}
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::getQuery — Get a query object
Get a query object to execute searches on the database
This function has no parameters.
Returns TokyoTyrantQuery on success and throws TokyoTyrantException on error
Example #1 TokyoTyrantTable::getQuery() example
<?php
/* Connect to a table database */
$table = new TokyoTyrantTable("localhost", 1979);
/* Put a few rows */
$table->put(null, array("column1" => "some data", "column2" => "more data"));
$table->put(null, array("something" => "value", "data" => "good data"));
/* Get query object */
$query = $table->getQuery();
/* Add condition to query */
$query->addCond('data', TokyoTyrant::RDBQC_STREQ, 'good data');
/* Get matching rows */
var_dump($query->search());
?>
The above example will output something similar to:
array(1) {
[11]=>
array(2) {
["something"]=>
string(5) "value"
["data"]=>
string(9) "good data"
}
}
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::out — Remove records
Removes records from a table database.
keysA single integer key or an array of integers
This method returns the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrantTable::out() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));
/* Delete the row */
$tt->out($index);
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::put — Store a row
$key
, array $columns
) : int
Puts a new row into the database. This method parameters are key which is
the primary key of the row, passing NULL will generate a new unique id. value
is an array containing the row contents which is usually key value pairs.
keyThe primary key of the row
columnsThe row contents
Returns the primary key on success and throws TokyoTyrantException on error
Example #1 TokyoTyrantTable::put() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));
/* Get the row back */
var_dump($tt->get($index));
/* Modify an existing row */
$tt->put($index, array("column1" => "other data", "column2" => "better data"));
/* Get the row back */
var_dump($tt->get($index));
?>
The above example will output:
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
array(2) {
["column1"]=>
string(10) "other data"
["column2"]=>
string(11) "better data"
}
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::putCat — Concatenates to a row
$key
, array $columns
) : voidThis method can be used to add new columns to existing records. Existing keys will be left unmodified but any new columns will be appended to the row. Passing null as key will generate a new row.
key
The primary key of the row or NULL
columnsArray of row contents
Returns the primary key and throws TokyoTyrantException on error.
Example #1 TokyoTyrantTable::putCat() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));
/* Get the row back */
var_dump($tt->get($index));
/* Modify an existing row */
$tt->putcat($index, array("column1" => "something new", "new_column" => "other data"));
/* Get the row back */
var_dump($tt->get($index));
?>
The above example will output:
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
array(3) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
["new_column"]=>
string(10) "other data"
}
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::putKeep — Put a new record
$key
, array $columns
) : voidPuts a new record into the database. If the key already exists this method throws an exception indicating that the records exists.
key
The primary key of the row or NULL
columnsArray of the row contents
Returns the primary key and throws TokyoTyrantException on error.
Example #1 TokyoTyrantTable::putKeep() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));
/* Get the row back */
var_dump($tt->get($index));
try {
$tt->putKeep($index, array("column1" => "something new", "new_column" => "other data"));
} catch (TokyoTyrantException $e) {
if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
echo "Existing record! Not modified\n";
} else {
echo "Error: " , $e->getMessage() , "\n";
}
}
/* Get the row back */
var_dump($tt->get($index));
?>
The above example will output something similar to:
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
Existing record! Not modified
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::putNr — Puts value
This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.
keysA string key or an array of key-value pairs
valueThe value in case a string key is used
This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::putShl — Concatenates to a record
$key
, string $value
, int $width
) : voidThis method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.
keyA string key
valueThe value to concatenate
widthThe width of the record
This method is not supported on table databases.
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantTable::setIndex — Sets index
Sets an index on a specified column. The index type is one of the TokyoTyrant::RDBIT_* constants.
Passing TokyoTyrant::RDBIT_VOID removes the index.
columnThe name of the column
typeThe index type
This method returns the current object and throws TokyoTyrantException on failure.
(PECL tokyo_tyrant >= 0.1.0)
This class is used to query the table databases
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::addCond — Adds a condition to the query
Adds a condition to the query. Condition can be something like: get all keys which value matches expr.
nameName of the column in the condition
op
The operator. One of the TokyoTyrant::RDBQC_* constants
exprThe expression
This method returns the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrantQuery::addCond() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Dump the search results */
var_dump($query->search());
?>
The above example will output:
array(2) {
[1]=>
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(14) "something here"
}
[4]=>
array(2) {
["column45"]=>
string(11) "random data"
["column2"]=>
string(25) "something along the lines"
}
}
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::__construct — Construct a new query
Construct a new query object
tableTokyoTyrantTable object with active database connection
Returns a new TokyoTyrantQuery object and throws TokyoTyrantException on error
Example #1 TokyoTyrantQuery::__construct() example
<?php
$tt = new TokyoTyrantTable("localhost", 1979);
$query = new TokyoTyrantQuery($tt);
/* Work with $query */
?>
(No version information available, might only be in Git)
TokyoTyrantQuery::count — Counts records
Returns a count of how many records a query returns.
This function has no parameters.
Returns a count of matching rows and throws TokyoTyrantException on error
Example #1 TokyoTyrantQuery::count() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Count the results */
var_dump($query->count());
?>
The above example will output:
int(2)
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::current — Returns the current element
Returns the current element. Part of Iterator interface
This function has no parameters.
Returns the current row
Example #1 TokyoTyrantQuery iterator example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2 pk: 4, columns: 2
(No version information available, might only be in Git)
TokyoTyrantQuery::hint — Get the hint string of the query
Get the hint string of the query. The hint string contains information about an executed query and it could be compared to for example MySQL EXPLAIN statement.
This function has no parameters.
This method always returns a string
Example #1 TokyoTyrantQuery::hint example
<?php
$tt = new TokyoTyrantTable("localhost", 1979);
$tt->vanish();
for ($i = 0; $i < 11; $i++) {
$tt->put(null, array('a_col' => 'a' . $i, 'b_col' => 'b' . $i));
}
$query = $tt->getQuery();
$query->addCond('a_col', TokyoTyrant::RDBQC_STRBW, 'a');
$query->search();
var_dump($query->hint());
?>
The above example will output something similar to:
string(72) " scanning the whole table result set size: 11 leaving the natural order "
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::key — Returns the current key
Returns the current key. Part of the Iterator interface
This function has no parameters.
Returns the current key and throws TokyoTyrantException on error
Example #1 TokyoTyrantQuery iterator example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2 pk: 4, columns: 2
(No version information available, might only be in Git)
TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries
$queries
, int $type
) : arrayExecutes multiple queries on a database and returns matching records. The current object is always the left most object in the search.
queriesArray of TokyoTyrantQuery objects
type
One of the TokyoTyrant::RDBMS_* constants
Returns the matching rows and throws TokyoTyrantException on error
Example #1 TokyoTyrantQuery::metaSearch() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add test data */
$tt->put('cherry', array('color' => 'red'));
$tt->put('strawberry', array('color' => 'red'));
$tt->put('apple', array('color' => 'green'));
$tt->put('lemon', array('color' => 'yellow'));
/* First query */
$query = $tt->getQuery();
$query->addCond('color', TokyoTyrant::RDBQC_STREQ, 'red')->setOrder('color', TokyoTyrant::RDBQO_STRASC);
/* Second query */
$query1 = $tt->getQuery();
$query1->addCond('color', TokyoTyrant::RDBQC_STREQ, 'yellow');
/* Get union between the queries */
var_dump($query->metaSearch(array($query1), TokyoTyrant::RDBMS_UNION));
?>
The above example will output:
array(3) {
["cherry"]=>
array(1) {
["color"]=>
string(3) "red"
}
["strawberry"]=>
array(1) {
["color"]=>
string(3) "red"
}
["lemon"]=>
array(1) {
["color"]=>
string(6) "yellow"
}
}
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::next — Moves the iterator to next entry
Returns the next result in the resultset. Part of the Iterator interface.
This function has no parameters.
Returns the next row and throws TokyoTyrantException on error.
Example #1 TokyoTyrantQuery iterator example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2 pk: 4, columns: 2
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::out — Removes records based on query
Removes all records that match the query. Works exactly like search but removes the records instead of returning them.
This function has no parameters.
This method returns the current object and throws TokyoTyrantException on failure.
Example #1 TokyoTyrantQuery::out() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Remove matching records */
$query->out();
?>
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::rewind — Rewinds the iterator
Rewind the resultset and executes the query if it has not been executed. Part of the Iterator interface.
This function has no parameters.
Returns TRUE
Example #1 TokyoTyrantQuery iterator example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2 pk: 4, columns: 2
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::search — Searches records
Executes a search on the table database. Returns an array of arrays containing the matching records. In the returned array the first level is the primary key of the data and the second level is the row data.
This function has no parameters.
Returns the matching rows and throws TokyoTyrantException on error
Example #1 TokyoTyrantQuery::search() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Dump the search results */
var_dump($query->search());
?>
The above example will output:
array(2) {
[1]=>
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(14) "something here"
}
[4]=>
array(2) {
["column45"]=>
string(11) "random data"
["column2"]=>
string(25) "something along the lines"
}
}
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::setLimit — Limit results
Set the maximum amount of records to return on a query.
maxMaximum amount of records. Default: -1
skipHow many records to skip from the start. Default: -1
This method returns the current object and throws TokyoTyrantException on failure.
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::setOrder — Orders results
Sets the order of a query
nameThe column name to apply the ordering on.
type
The type can be one of the following
constants:
TokyoTyrant::RDBQO_STRASC - String ascending
TokyoTyrant::RDBQO_STRDESC - String descending
TokyoTyrant::RDBQO_NUMASC - Numberic ascending
TokyoTyrant::RDBQO_NUMDESC - String descending
This method returns the current object.
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantQuery::valid — Checks the validity of current item
Checks if the current item is valid. Part of the Iterator interface
This function has no parameters.
Returns TRUE if the current item is valid and FALSE if not.
Example #1 TokyoTyrantQuery iterator example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));
/* Get a new query object */
$query = $tt->getQuery();
/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");
/* Iterate the results */
foreach ($query as $key => $value) {
echo "pk: $key, columns: ", count($value) ,"\n";
}
?>
The above example will output something similar to:
pk: 1, columns: 2 pk: 4, columns: 2
(PECL tokyo_tyrant >= 0.2.0)
Provides an iterator for TokyoTyrant and TokyoTyrantTable objects. The iterator iterates over all keys and values in the database. TokyoTyrantIterator was added in version 0.2.0.
$host
[, int $port = TokyoTyrant::RDBDEF_PORT
[, array $options
]] ) : TokyoTyrant$host
[, int $port = TokyoTyrant::RDBDEF_PORT
[, array $options
]]] )$log_dir
, int $timestamp
[, bool $check_consistency = TRUE
] ) : mixed$host
, int $port
, int $timestamp
[, bool $check_consistency = TRUE
] ) : mixed$timeout
[, int $options = TokyoTyrant::RDBT_RECON
] ) : TokyoTyrant(PECL tokyo_tyrant >= 0.2.0)
TokyoTyrantIterator::__construct — Construct an iterator
Construct a new TokyoTyrantIterator object. One connection can have multiple iterators but it is not quaranteed
that all items are traversed in that case. object parameter can be either an of instance
TokyoTyrant or TokyoTyrantTable.
This function has no parameters.
Throws an exception if iterator initialization fails.
Example #1 TokyoTyrantIterator::__construct() example
<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);
/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));
/* Construct an iterator */
$it = new TokyoTyrantIterator($tt);
foreach ($it as $value) {
var_dump($value);
}
?>
The above example will output:
array(2) {
["column1"]=>
string(9) "some data"
["column2"]=>
string(9) "more data"
}
(PECL tokyo_tyrant >= 0.2.0)
TokyoTyrantIterator::current — Get the current value
Returns the current value during iteration.
This function has no parameters.
Returns the current value on success and false on failure.
(PECL tokyo_tyrant >= 0.2.0)
TokyoTyrantIterator::key — Returns the current key
This function has no parameters.
Returns the current key on success and false on failure.
(PECL tokyo_tyrant >= 0.2.0)
TokyoTyrantIterator::next — Move to next key
Move to next key during iteration and return it's value.
This function has no parameters.
Returns the next value on success and false on failure.
(PECL tokyo_tyrant >= 0.2.0)
TokyoTyrantIterator::rewind — Rewinds the iterator
Rewinds the iterator for new iteration. Called automatically at the beginning of foreach.
This function has no parameters.
Throws TokyoTyrantException if iterator initialization fails.
(PECL tokyo_tyrant >= 0.2.0)
TokyoTyrantIterator::valid — Rewinds the iterator
Checks whether the internal pointer points to valid element.
This function has no parameters.
Returns TRUE if the current item is valid and FALSE if not.
(PECL tokyo_tyrant >= 0.1.0)
TokyoTyrantException
The exception code. This can be compared to TokyoTyrant::TTE_* constants
The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit » http://www.hermetic.ch/cal_stud/jdn.htm. For more information on calendar systems visit » http://www.fourmilab.ch/documents/calendar/. Excerpts from this page are included in these instructions, and are in quotes.
No external libraries are needed to build this extension.
To get these functions to work, you have to compile PHP with --enable-calendar.
The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
CAL_EASTER_DEFAULT
(integer)
CAL_EASTER_ROMAN
(integer)
CAL_EASTER_ALWAYS_GREGORIAN
(integer)
CAL_EASTER_ALWAYS_JULIAN
(integer)
CAL_GREGORIAN
(integer)
CAL_JULIAN
(integer)
CAL_JEWISH
(integer)
CAL_FRENCH
(integer)
CAL_NUM_CALS
(integer)
CAL_JEWISH_ADD_ALAFIM_GERESH
(integer)
CAL_JEWISH_ADD_ALAFIM
(integer)
CAL_JEWISH_ADD_GERESHAYIM
(integer)
CAL_DOW_DAYNO
(integer)
0 means Sunday and
6 means Saturday.
CAL_DOW_SHORT
(integer)
CAL_DOW_LONG
(integer)
CAL_MONTH_GREGORIAN_SHORT
(integer)
CAL_MONTH_GREGORIAN_LONG
(integer)
CAL_MONTH_JULIAN_SHORT
(integer)
CAL_MONTH_JULIAN_LONG
(integer)
CAL_MONTH_JEWISH
(integer)
CAL_MONTH_FRENCH
(integer)
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
cal_days_in_month — Return the number of days in a month for a given year and calendar
$calendar
, int $month
, int $year
) : int
This function will return the number of days in the
month of year for
the specified calendar.
calendarCalendar to use for calculation
monthMonth in the selected calendar
yearYear in the selected calendar
The length in days of the selected month in the given calendar
Example #1 cal_days_in_month() example
<?php
$number = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There were {$number} days in August 2003";
?>
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
cal_from_jd — Converts from Julian Day Count to a supported calendar
$jd
, int $calendar
) : array
cal_from_jd() converts the Julian day given in
jd into a date of the specified
calendar. Supported
calendar values are
CAL_GREGORIAN,
CAL_JULIAN,
CAL_JEWISH and
CAL_FRENCH.
jdJulian day as integer
calendarCalendar to convert to
Returns an array containing calendar information like month, day, year,
day of week (dow), abbreviated and full names of weekday and month and the
date in string form "month/day/year".
The day of week ranges from 0 (Sunday) to
6 (Saturday).
Example #1 cal_from_jd() example
<?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?>
The above example will output:
Array
(
[date] => 8/16/2003
[month] => 8
[day] => 16
[year] => 2003
[dow] => 6
[abbrevdayname] => Sat
[dayname] => Saturday
[abbrevmonth] => Aug
[monthname] => August
)
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
cal_info — Returns information about a particular calendar
$calendar = -1
] ) : array
cal_info() returns information on the
specified calendar.
Calendar information is returned as an array containing the
elements calname, calsymbol,
month, abbrevmonth and
maxdaysinmonth. The names of the different calendars
which can be used as calendar are as follows:
CAL_GREGORIAN - Gregorian Calendar
CAL_JULIAN - Julian Calendar
CAL_JEWISH - Jewish Calendar
CAL_FRENCH - French Revolutionary Calendar
If no calendar is specified information on all
supported calendars is returned as an array.
calendarCalendar to return information for. If no calendar is specified information about all calendars is returned.
Example #1 cal_info() example
<?php
$info = cal_info(0);
print_r($info);
?>
The above example will output:
Array
(
[months] => Array
(
[1] => January
[2] => February
[3] => March
[4] => April
[5] => May
[6] => June
[7] => July
[8] => August
[9] => September
[10] => October
[11] => November
[12] => December
)
[abbrevmonths] => Array
(
[1] => Jan
[2] => Feb
[3] => Mar
[4] => Apr
[5] => May
[6] => Jun
[7] => Jul
[8] => Aug
[9] => Sep
[10] => Oct
[11] => Nov
[12] => Dec
)
[maxdaysinmonth] => 31
[calname] => Gregorian
[calsymbol] => CAL_GREGORIAN
)
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
cal_to_jd — Converts from a supported calendar to Julian Day Count
$calendar
, int $month
, int $day
, int $year
) : int
cal_to_jd() calculates the Julian day count
for a date in the specified calendar.
Supported calendars are
CAL_GREGORIAN,
CAL_JULIAN,
CAL_JEWISH and
CAL_FRENCH.
calendar
Calendar to convert from, one of
CAL_GREGORIAN,
CAL_JULIAN,
CAL_JEWISH or
CAL_FRENCH.
month
The month as a number, the valid range depends
on the calendar
day
The day as a number, the valid range depends
on the calendar
year
The year as a number, the valid range depends
on the calendar
A Julian Day number.
(PHP 4, PHP 5, PHP 7)
easter_date — Get Unix timestamp for midnight on Easter of a given year
$year = date("Y")
[, int $method = CAL_EASTER_DEFAULT
]] ) : intReturns the Unix timestamp corresponding to midnight on Easter of the given year.
This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. typically before 1970 or after 2037 on 32bit systems).
The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.
yearThe year as a number between 1970 an 2037. If omitted, defaults to the current year according to the local time.
method
Allows Easter dates to be calculated based on the Julian calendar when set
to CAL_EASTER_ALWAYS_JULIAN. See also calendar constants.
The easter date as a unix timestamp.
Example #1 easter_date() example
<?php
echo date("M-d-Y", easter_date(1999)); // Apr-04-1999
echo date("M-d-Y", easter_date(2000)); // Apr-23-2000
echo date("M-d-Y", easter_date(2001)); // Apr-15-2001
?>
Note:
easter_date() relies on your system's C library time functions, rather than using PHP's internal date and time functions. As a consequence, easter_date() uses the
TZenvironment variable to determine the time zone it should operate in, rather than using PHP's default time zone, which may result in unexpected behaviour when using this function in conjunction with other date functions in PHP.As a workaround, you can use the easter_days() with DateTime and DateInterval to calculate the start of Easter in your PHP time zone as follows:
<?php
function get_easter_datetime($year) {
$base = new DateTime("$year-03-21");
$days = easter_days($year);
return $base->add(new DateInterval("P{$days}D"));
}
foreach (range(2012, 2015) as $year) {
printf("Easter in %d is on %s\n",
$year,
get_easter_datetime($year)->format('F j'));
}
?>The above example will output:
Easter in 2012 is on April 8 Easter in 2013 is on March 31 Easter in 2014 is on April 20 Easter in 2015 is on April 5
(PHP 4, PHP 5, PHP 7)
easter_days — Get number of days after March 21 on which Easter falls for a given year
$year = date("Y")
[, int $method = CAL_EASTER_DEFAULT
]] ) : intReturns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.
This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).
The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.
yearThe year as a positive number. If omitted, defaults to the current year according to the local time.
method
Allows Easter dates to be calculated based
on the Gregorian calendar during the years 1582 - 1752 when set to
CAL_EASTER_ROMAN. See the calendar constants for more valid
constants.
The number of days after March 21st that the Easter Sunday
is in the given year.
Example #1 easter_days() example
<?php
echo easter_days(1999); // 14, i.e. April 4
echo easter_days(1492); // 32, i.e. April 22
echo easter_days(1913); // 2, i.e. March 23
?>
(PHP 4, PHP 5, PHP 7)
frenchtojd — Converts a date from the French Republican Calendar to a Julian Day Count
$month
, int $day
, int $year
) : intConverts a date from the French Republican Calendar to a Julian Day Count.
These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.
monthThe month as a number from 1 (for Vendémiaire) to 13 (for the period of 5-6 days at the end of each year)
dayThe day as a number from 1 to 30
yearThe year as a number between 1 and 14
The julian day for the given french revolution date as an integer.
(PHP 4, PHP 5, PHP 7)
gregoriantojd — Converts a Gregorian date to Julian Day Count
$month
, int $day
, int $year
) : intThe valid range for the Gregorian calendar is from November 25, 4714 B.C. to at least December 31, 9999 A.D.
Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.
monthThe month as a number from 1 (for January) to 12 (for December)
dayThe day as a number from 1 to 31. If the month has less days then given, overflow occurs; see the example below.
year
The year as a number between -4714 and 9999.
Negative numbers mean years B.C., positive numbers mean years A.D.
Note that there is no year 0; December 31, 1 B.C. is
immediately followed by January 1, 1 A.D.
The julian day for the given gregorian date as an integer.
Dates outside the valid range return 0.
Example #1 Calendar functions
<?php
$jd = gregoriantojd(10, 11, 1970);
echo "$jd\n";
$gregorian = jdtogregorian($jd);
echo "$gregorian\n";
?>
The above example will output:
2440871 10/11/1970
Example #2 Overflow behavior
<?php
echo gregoriantojd(2, 31, 2018), PHP_EOL,
gregoriantojd(3, 3, 2018), PHP_EOL;
?>
The above example will output:
2458181 2458181
(PHP 4, PHP 5, PHP 7)
jddayofweek — Returns the day of the week
Returns the day of the week. Can return a string or an integer depending on the mode.
juliandayA julian day number as integer
mode| Mode | Meaning |
|---|---|
| 0 (Default) | Return the day number as an int (0=Sunday, 1=Monday, etc) |
| 1 | Returns string containing the day of week (English-Gregorian) |
| 2 | Return a string containing the abbreviated day of week (English-Gregorian) |
The gregorian weekday as either an integer or string.
(PHP 4, PHP 5, PHP 7)
jdmonthname — Returns a month name
$julianday
, int $mode
) : string
Returns a string containing a month name.
mode tells this function which calendar to
convert the Julian Day Count to, and what type of month names are
to be returned.
| Mode | Meaning | Values |
|---|---|---|
CAL_MONTH_GREGORIAN_SHORT |
Gregorian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
CAL_MONTH_GREGORIAN_LONG |
Gregorian | January, February, March, April, May, June, July, August, September, October, November, December |
CAL_MONTH_JULIAN_SHORT |
Julian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
CAL_MONTH_JULIAN_LONG |
Julian | January, February, March, April, May, June, July, August, September, October, November, December |
CAL_MONTH_JEWISH |
Jewish | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul |
CAL_MONTH_FRENCH |
French Republican | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra |
jdayThe Julian Day to operate on
modeThe calendar mode (see table above).
The month name for the given Julian Day and mode.
(PHP 4, PHP 5, PHP 7)
jdtofrench — Converts a Julian Day Count to the French Republican Calendar
$juliandaycount
) : stringConverts a Julian Day Count to the French Republican Calendar.
juliandayA julian day number as integer
The french revolution date as a string in the form "month/day/year"
(PHP 4, PHP 5, PHP 7)
jdtogregorian — Converts Julian Day Count to Gregorian date
$julianday
) : stringConverts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".
juliandayA julian day number as integer
The gregorian date as a string in the form "month/day/year"
(PHP 4, PHP 5, PHP 7)
jdtojewish — Converts a Julian day count to a Jewish calendar date
$juliandaycount
[, bool $hebrew = FALSE
[, int $fl = 0
]] ) : stringConverts a Julian Day Count to the Jewish Calendar.
juliandayA julian day number as integer
hebrew
If the hebrew parameter is set to TRUE, the
fl parameter is used for Hebrew, ISO-8859-8 encoded string based,
output format.
fl
A bitmask which may consist of
CAL_JEWISH_ADD_ALAFIM_GERESH,
CAL_JEWISH_ADD_ALAFIM and
CAL_JEWISH_ADD_GERESHAYIM.
The Jewish date as a string in the form "month/day/year", or an ISO-8859-8
encoded Hebrew date string, according to the hebrew
parameter.
Example #1 jdtojewish() Example
<?php
$jd = gregoriantojd(10, 8, 2002);
echo jdtojewish($jd, true), PHP_EOL,
jdtojewish($jd, true, CAL_JEWISH_ADD_GERESHAYIM), PHP_EOL,
jdtojewish($jd, true, CAL_JEWISH_ADD_ALAFIM), PHP_EOL,
jdtojewish($jd, true,CAL_JEWISH_ADD_ALAFIM_GERESH), PHP_EOL;
?>
The above example will output:
ב חשון התשסג ב' חשון התשס"ג ב חשון ה אלפים תשסג ב חשון ה'תשסג
(PHP 4, PHP 5, PHP 7)
jdtojulian — Converts a Julian Day Count to a Julian Calendar Date
$julianday
) : stringConverts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".
juliandayA julian day number as integer
The julian date as a string in the form "month/day/year"
(PHP 4, PHP 5, PHP 7)
jdtounix — Convert Julian Day to Unix timestamp
$jday
) : int
This function will return a Unix timestamp corresponding to the
Julian Day given in jday or FALSE if
jday is not inside the Unix epoch
(Gregorian years between 1970 and 2037 or 2440588 <=
jday <= 2465342 ). The time returned is
UTC.
jdayA julian day number between 2440588 and 2465342.
The unix timestamp for the start (midnight, not noon) of the given Julian day.
(PHP 4, PHP 5, PHP 7)
jewishtojd — Converts a date in the Jewish Calendar to Julian Day Count
$month
, int $day
, int $year
) : intAlthough this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.
month
The month as a number from 1 to 13,
where 1 means Tishri,
13 means Elul, and
6 and 7 mean
Adar in regular years, but Adar I
and Adar II, respectively, in leap years.
day
The day as a number from 1 to 30.
If the month has only 29 days, the first day of the following month is
assumed.
yearThe year as a number between 1 and 9999
The julian day for the given jewish date as an integer.
(PHP 4, PHP 5, PHP 7)
juliantojd — Converts a Julian Calendar date to Julian Day Count
$month
, int $day
, int $year
) : intValid Range for Julian Calendar 4713 B.C. to 9999 A.D.
Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.
Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.
monthThe month as a number from 1 (for January) to 12 (for December)
dayThe day as a number from 1 to 31
yearThe year as a number between -4713 and 9999
The julian day for the given julian date as an integer.
(PHP 4, PHP 5, PHP 7)
unixtojd — Convert Unix timestamp to Julian Day
$timestamp = time()
] ) : int
Return the Julian Day for a Unix timestamp
(seconds since 1.1.1970), or for the current day if no
timestamp is given. Either way, the time is regarded
as local time (not UTC).
timestampA unix timestamp to convert.
A julian day number as integer.
These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.
The date and time information is internally stored as a 64-bit number so all conceivably useful dates (including negative years) are supported. The range is from about 292 billion years in the past to the same in the future.
Note: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g.
$date = $date->modify('+7 days')and not$date += 7*24*60*60) and leap years into consideration when working with these functions.
Note: The timezones referenced in this section can be found in the List of Supported Timezones.
No external libraries are needed to build this extension.
There is no installation needed to use these functions; they are part of the PHP core.
Note: Getting the latest timezone database
The latest version of the timezone database can be installed via PECL's » timezonedb.
Note: Experimental DateTime support in PHP 5.1.x
Although the DateTime class (and related functions) are enabled by default since PHP 5.2.0, it is possible to add experimental support into PHP 5.1.x by using the following flag before configure/compile:
CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| date.default_latitude | "31.7667" | PHP_INI_ALL | |
| date.default_longitude | "35.2333" | PHP_INI_ALL | |
| date.sunrise_zenith | "90.583333" | PHP_INI_ALL | |
| date.sunset_zenith | "90.583333" | PHP_INI_ALL | |
| date.timezone | "" | PHP_INI_ALL | Available as of PHP 5.1.0. |
Here's a short explanation of the configuration directives.
date.default_latitude
float
The default latitude.
date.default_longitude
float
The default longitude.
date.sunrise_zenith
float
The default sunrise zenith.
date.sunset_zenith
float
The default sunset zenith.
date.timezone
string
The default timezone used by all date/time functions. Prior to PHP 5.4.0, this would only work if the TZ environment variable was not set. The precedence order for which timezone is used if none is explicitly mentioned is described in the date_default_timezone_get() page. See List of Supported Timezones for a list of supported timezones.
Note: The first four configuration options are currently only used by date_sunrise() and date_sunset().
This extension has no resource types defined.
The DATE_
constants are defined since PHP 5.1.1 and they offer standard
date representations, which can be used along with the date format functions
(like date()).
Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().
The following examples show some pitfalls of Date/Time arithmetic with regard to DST transitions and months having different numbers of days.
Example #1 DateTimeImmutable::add/sub add intervals which cover elapsed time
Adding PT24H over a DST transition will appear to add 23/25 hours (for most timezones).
<?php
$dt = new DateTimeImmutable("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->add(new DateInterval("PT3H"));
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>
The above example will output:
Start: 2015-11-01 00:00:00 -04:00 End: 2015-11-01 02:00:00 -05:00
Example #2 DateTimeImmutable::modify and strtotime increment or decrement individual component values
Adding +24 hours over a DST transition will add exactly 24 hours as seen in the date/time string (unless the start or end time is on a transition point).
<?php
$dt = new DateTimeImmutable("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("+24 hours");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>
The above example will output:
Start: 2015-11-01 00:00:00 -04:00 End: 2015-11-02 00:00:00 -05:00
Example #3 Adding or subtracting times can over- or underflow dates
Like where January 31st + 1 month will result in March 2nd (leap year) or 3rd (normal year).
<?php
echo "Normal year:\n"; // February has 28 days
$dt = new DateTimeImmutable("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("+1 month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
echo "Leap year:\n"; // February has 29 days
$dt = new DateTimeImmutable("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("+1 month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>
The above example will output:
Normal year: Start: 2015-01-31 00:00:00 -05:00 End: 2015-03-03 00:00:00 -05:00 Leap year: Start: 2016-01-31 00:00:00 -05:00 End: 2016-03-02 00:00:00 -05:00
To get the last day of the next month (i.e. to prevent the overflow),
the last day of format is available as of PHP 5.3.0.
<?php
echo "Normal year:\n"; // February has 28 days
$dt = new DateTimeImmutable("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("last day of next month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
echo "Leap year:\n"; // February has 29 days
$dt = new DateTimeImmutable("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("last day of next month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>
The above example will output:
Normal year: Start: 2015-01-31 00:00:00 -05:00 End: 2015-02-28 00:00:00 -05:00 Leap year: Start: 2016-01-31 00:00:00 -05:00 End: 2016-02-29 00:00:00 -05:00
(PHP 5 >= 5.2.0, PHP 7)
This class behaves the same as DateTimeImmutable except objects are modified itself when modification methods such as DateTime::modify() are called.
$format
, string $datetime
[, DateTimeZone $timezone
] ) : DateTime
| Version | Description |
|---|---|
| 7.2.0 | The class constants of DateTime are now defined on DateTimeInterface. |
| 7.0.0 | Added constants: DATE_RFC3339_EXTENDED and DateTime::RFC3339_EXTENDED. |
| 5.5.0 | The class now implements DateTimeInterface. |
| 5.4.24 | The COOKIE constant was changed to reflect RFC 1036 using a four digit year rather than a two digit year (RFC 850) as prior versions. |
| 5.2.2 |
DateTime object comparison with the
comparison operators
changed to work as expected. Previously, all DateTime objects were
considered equal (using ==).
|
(PHP 5 >= 5.3.0, PHP 7)
DateTime::add -- date_add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
Object oriented style
Procedural style
Adds the specified DateInterval object to the specified DateTime object.
objectProcedural style only: A DateTime object returned by date_create(). The function modifies this object.
interval
A DateInterval object
Returns the DateTime object for method chaining or FALSE on failure.
Example #1 DateTime::add() example
Object oriented style
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>
Procedural style
<?php
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>
The above examples will output:
2000-01-11
Example #2 Further DateTime::add() examples
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>
The above example will output:
2000-01-01 10:00:30 2007-06-05 04:03:02
Example #3 Beware when adding months
<?php
$date = new DateTime('2000-12-31');
$interval = new DateInterval('P1M');
$date->add($interval);
echo $date->format('Y-m-d') . "\n";
$date->add($interval);
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-01-31 2001-03-03
DateTime::modify() is an alternative when using PHP 5.2.
(PHP 5 >= 5.2.0, PHP 7)
DateTime::__construct -- date_create — Returns new DateTime object
Object oriented style
Procedural style
Returns new DateTime object.
datetimeA date/time string. Valid formats are explained in Date and Time Formats.
Enter "now" here to obtain the current time when using
the $timezone parameter.
timezone
A DateTimeZone object representing the
timezone of $datetime.
If $timezone is omitted,
the current timezone will be used.
Note:
The
$timezoneparameter and the current timezone are ignored when the$datetimeparameter either is a UNIX timestamp (e.g.@946684800) or specifies a timezone (e.g.2010-01-28T15:00:00+02:00).
Returns a new DateTime instance.
Procedural style returns FALSE on failure.
Emits Exception in case of an error.
| Version | Description |
|---|---|
| 7.1 | From now on microseconds are filled with actual value. Not with '00000'. |
| 5.3.0 |
If datetime contains an invalid
date/time format, then an
exception is now thrown. Previously an error was emitted.
|
Example #1 DateTime::__construct() example
Object oriented style
<?php
try {
$date = new DateTime('2000-01-01');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
echo $date->format('Y-m-d');
?>
Procedural style
<?php
$date = date_create('2000-01-01');
if (!$date) {
$e = date_get_last_errors();
foreach ($e['errors'] as $error) {
echo "$error\n";
}
exit(1);
}
echo date_format($date, 'Y-m-d');
?>
The above examples will output:
2000-01-01
Example #2 Intricacies of DateTime::__construct()
<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Using a UNIX timestamp. Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
The above example will output something similar to:
2000-01-01 00:00:00-05:00 2000-01-01 00:00:00+12:00 2010-04-24 10:24:16-04:00 2010-04-25 02:24:16+12:00 2000-01-01 00:00:00+00:00 2000-03-01 00:00:00-05:00
(PHP 5 >= 5.3.0, PHP 7)
DateTime::createFromFormat -- date_create_from_format — Parses a time string according to a specified format
Object oriented style
$format
, string $datetime
[, DateTimeZone $timezone
] ) : DateTimeProcedural style
$format
, string $datetime
[, DateTimeZone $timezone
] ) : DateTime
Returns a new DateTime object representing the date and time specified by the
datetime string, which was formatted in the given
format.
formatThe format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.
format character |
Description | Example parsable values |
|---|---|---|
| Day | --- | --- |
d and j |
Day of the month, 2 digits with or without leading zeros |
01 to 31 or
1 to 31
|
D and l |
A textual representation of a day |
Mon through Sun or
Sunday through Saturday
|
S |
English ordinal suffix for the day of the month, 2 characters. It's ignored while processing. |
st, nd, rd or
th.
|
z |
The day of the year (starting from 0) | 0 through 365 |
| Month | --- | --- |
F and M |
A textual representation of a month, such as January or Sept |
January through December or
Jan through Dec
|
m and n |
Numeric representation of a month, with or without leading zeros |
01 through 12 or
1 through 12
|
| Year | --- | --- |
Y |
A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
y |
A two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive) |
Examples:
99 or 03
(which will be interpreted as 1999 and
2003, respectively)
|
| Time | --- | --- |
a and A |
Ante meridiem and Post meridiem | am or pm |
g and h |
12-hour format of an hour with or without leading zero |
1 through 12 or
01 through 12
|
G and H |
24-hour format of an hour with or without leading zeros |
0 through 23 or
00 through 23
|
i |
Minutes with leading zeros | 00 to 59 |
s |
Seconds, with leading zeros | 00 through 59 |
v |
Milliseconds (up to three digits) | Example: 12, 345 |
u |
Microseconds (up to six digits) | Example: 45, 654321 |
| Timezone | --- | --- |
e, O,
P and T
|
Timezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation | Examples: UTC, GMT,
Atlantic/Azores or
+0200 or +02:00 or
EST, MDT
|
| Full Date/Time | --- | --- |
U |
Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | Example: 1292177455 |
| Whitespace and Separators | --- | --- |
(space) |
One space or one tab | Example: |
# |
One of the following separation symbol: ;,
:, /, .,
,, -, ( or
)
|
Example: / |
;,
:, /, .,
,, -, ( or
)
|
The specified character. | Example: - |
? |
A random byte | Example: ^ (Be aware that for UTF-8
characters you might need more than one ?.
In this case, using * is probably what you want
instead) |
* |
Random bytes until the next separator or digit | Example: * in Y-*-d with
the string 2009-aWord-08 will match
aWord |
! |
Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to the Unix Epoch | Without !, all fields will be set to the
current date and time. |
| |
Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to the Unix Epoch if they have not been parsed yet | Y-m-d| will set the year, month and day
to the information found in the string to parse, and sets the hour,
minute and second to 0. |
+ |
If this format specifier is present, trailing data in the string will not cause an error, but a warning instead | Use DateTime::getLastErrors() to find out whether trailing data was present. |
Unrecognized characters in the format string will cause the parsing to fail and an error message is appended to the returned structure. You can query error messages with DateTime::getLastErrors().
To include literal characters in format, you have
to escape them with a backslash (\).
If format does not contain the character
! then portions of the generated time which are not
specified in format will be set to the current
system time.
If format contains the
character !, then portions of the generated
time not provided in format, as well as
values to the left-hand side of the !, will
be set to corresponding values from the Unix epoch.
The Unix epoch is 1970-01-01 00:00:00 UTC.
datetimeString representing the time.
timezoneA DateTimeZone object representing the desired time zone.
If timezone is omitted and
datetime contains no timezone,
the current timezone will be used.
Note:
The
timezoneparameter and the current timezone are ignored when thedatetimeparameter either contains a UNIX timestamp (e.g.946684800) or specifies a timezone (e.g.2010-01-28T15:00:00+02:00).
Returns a new DateTime instance or FALSE on failure.
| Version | Description |
|---|---|
| 7.3.0 |
The v format specifier has been added.
|
| 5.3.9 |
The + format specifier has been added.
|
Example #1 DateTime::createFromFormat() example
Object oriented style
<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');
?>
Procedural style
<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');
?>
The above examples will output:
2009-02-15
Example #2 Intricacies of DateTime::createFromFormat()
<?php
echo 'Current time: ' . date('Y-m-d H:i:s') . "\n";
$format = 'Y-m-d';
$date = DateTime::createFromFormat($format, '2009-02-15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = 'Y-m-!d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = '!d';
$date = DateTime::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
?>
The above example will output something similar to:
Current time: 2010-04-23 10:29:35 Format: Y-m-d; 2009-02-15 10:29:35 Format: Y-m-d H:i:s; 2009-02-15 15:16:17 Format: Y-m-!d H:i:s; 1970-01-15 15:16:17 Format: !d; 1970-01-15 00:00:00
Example #3 Format string with literal characters
<?php
echo DateTime::createFromFormat('H\h i\m s\s','23h 15m 03s')->format('H:i:s');
?>
The above example will output something similar to:
23:15:03
(PHP 7 >= 7.3.0)
DateTime::createFromImmutable — Returns new DateTime object encapsulating the given DateTimeImmutable object
objectThe immutable DateTimeImmutable object that needs to be converted to a mutable version. This object is not modified, but instead a new DateTime object is created containing the same date, time, and timezone information.
Example #1 Creating a mutable date time object
<?php
$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");
$mutable = DateTime::createFromImmutable( $date );
?>
Returns a new DateTime instance.
(PHP 5 >= 5.3.0, PHP 7)
DateTime::getLastErrors -- date_get_last_errors — Returns the warnings and errors
Object oriented style
Procedural style
Returns an array of warnings and errors found while parsing a date/time string.
This function has no parameters.
Returns array containing info about warnings and errors.
Example #1 DateTime::getLastErrors() example
Object oriented style
<?php
try {
$date = new DateTime('asdfasdf');
} catch (Exception $e) {
// For demonstration purposes only...
print_r(DateTime::getLastErrors());
// The real object oriented way to do this is
// echo $e->getMessage();
}
?>
Procedural style
<?php
$date = date_create('asdfasdf');
print_r(date_get_last_errors());
?>
The above examples will output:
Array
(
[warning_count] => 1
[warnings] => Array
(
[6] => Double timezone specification
)
[error_count] => 1
[errors] => Array
(
[0] => The timezone could not be found in the database
)
)
The indexes 6, and 0 in the example output refer to the character index in the string where the error occurred.
(PHP 5 >= 5.2.0, PHP 7)
DateTime::modify -- date_modify — Alters the timestamp
Object oriented style
Procedural style
Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by DateTimeImmutable::__construct().
objectProcedural style only: A DateTime object returned by date_create(). The function modifies this object.
modifierA date/time string. Valid formats are explained in Date and Time Formats.
Returns the DateTime object for method chaining or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.6 | Absolute date/time statements now take effect. Previously, only relative parts were used. |
| 5.3.0 | Changed the
return value on success from NULL to DateTime. |
Example #1 DateTime::modify() example
Object oriented style
<?php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
?>
Procedural style
<?php
$date = date_create('2006-12-12');
date_modify($date, '+1 day');
echo date_format($date, 'Y-m-d');
?>
The above examples will output:
2006-12-13
Example #2 Beware when adding or subtracting months
<?php
$date = new DateTime('2000-12-31');
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-01-31 2001-03-03
(PHP 5 >= 5.3.0, PHP 7)
DateTime::__set_state — The __set_state handler
The __set_state() handler.
arrayInitialization array.
Returns a new instance of a DateTime object.
(PHP 5 >= 5.2.0, PHP 7)
DateTime::setDate -- date_date_set — Sets the date
Object oriented style
Procedural style
Resets the current date of the DateTime object to a different date.
objectProcedural style only: A DateTime object returned by date_create(). The function modifies this object.
yearYear of the date.
monthMonth of the date.
dayDay of the date.
Returns the DateTime object for method chaining or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.0 | Changed the
return value on success from NULL to DateTime. |
Example #1 DateTime::setDate() example
Object oriented style
<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>
Procedural style
<?php
$date = date_create();
date_date_set($date, 2001, 2, 3);
echo date_format($date, 'Y-m-d');
?>
The above examples will output:
2001-02-03
Example #2 Values exceeding ranges are added to their parent values
<?php
$date = new DateTime();
$date->setDate(2001, 2, 28);
echo $date->format('Y-m-d') . "\n";
$date->setDate(2001, 2, 29);
echo $date->format('Y-m-d') . "\n";
$date->setDate(2001, 14, 3);
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-02-28 2001-03-01 2002-02-03
(PHP 5 >= 5.2.0, PHP 7)
DateTime::setISODate -- date_isodate_set — Sets the ISO date
Object oriented style
Procedural style
Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.
objectProcedural style only: A DateTime object returned by date_create(). The function modifies this object.
yearYear of the date.
weekWeek of the date.
dayOfWeekOffset from the first day of the week.
Returns the DateTime object for method chaining or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.0 | Changed the
return value on success from NULL to DateTime. |
Example #1 DateTime::setISODate() example
Object oriented style
<?php
$date = new DateTime();
$date->setISODate(2008, 2);
echo $date->format('Y-m-d') . "\n";
$date->setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";
?>
Procedural style
<?php
$date = date_create();
date_isodate_set($date, 2008, 2);
echo date_format($date, 'Y-m-d') . "\n";
date_isodate_set($date, 2008, 2, 7);
echo date_format($date, 'Y-m-d') . "\n";
?>
The above examples will output:
2008-01-07 2008-01-13
Example #2 Values exceeding ranges are added to their parent values
<?php
$date = new DateTime();
$date->setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";
$date->setISODate(2008, 2, 8);
echo $date->format('Y-m-d') . "\n";
$date->setISODate(2008, 53, 7);
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2008-01-13 2008-01-14 2009-01-04
Example #3 Finding the month a week is in
<?php
$date = new DateTime();
$date->setISODate(2008, 14);
echo $date->format('n');
?>
The above examples will output:
3
(PHP 5 >= 5.2.0, PHP 7)
DateTime::setTime -- date_time_set — Sets the time
Object oriented style
$hour
, int $minute
[, int $second = 0
[, int $microsecond = 0
]] ) : DateTimeProcedural style
$object
, int $hour
, int $minute
[, int $second = 0
[, int $microsecond = 0
]] ) : DateTimeResets the current time of the DateTime object to a different time.
objectProcedural style only: A DateTime object returned by date_create(). The function modifies this object.
hourHour of the time.
minuteMinute of the time.
secondSecond of the time.
microsecondMicrosecond of the time.
Returns the DateTime object for method chaining or FALSE on failure.
| Version | Description |
|---|---|
| 7.1.0 | The microsecond parameter was added. |
| 5.3.0 | Changed the
return value on success from NULL to DateTime. |
Example #1 DateTime::setTime() example
Object oriented style
<?php
$date = new DateTime('2001-01-01');
$date->setTime(14, 55);
echo $date->format('Y-m-d H:i:s') . "\n";
$date->setTime(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
?>
Procedural style
<?php
$date = date_create('2001-01-01');
date_time_set($date, 14, 55);
echo date_format($date, 'Y-m-d H:i:s') . "\n";
date_time_set($date, 14, 55, 24);
echo date_format($date, 'Y-m-d H:i:s') . "\n";
?>
The above examples will output something similar to:
2001-01-01 14:55:00 2001-01-01 14:55:24
Example #2 Values exceeding ranges are added to their parent values
<?php
$date = new DateTime('2001-01-01');
$date->setTime(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
$date->setTime(14, 55, 65);
echo $date->format('Y-m-d H:i:s') . "\n";
$date->setTime(14, 65, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
$date->setTime(25, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
?>
The above example will output:
2001-01-01 14:55:24 2001-01-01 14:56:05 2001-01-01 15:05:24 2001-01-02 01:55:24
(PHP 5 >= 5.3.0, PHP 7)
DateTime::setTimestamp -- date_timestamp_set — Sets the date and time based on an Unix timestamp
Object oriented style
Procedural style
Sets the date and time based on an Unix timestamp.
objectProcedural style only: A DateTime object returned by date_create(). The function modifies this object.
timestampUnix timestamp representing the date.
Returns the DateTime object for method chaining or FALSE on failure.
Example #1 DateTime::setTimestamp() example
Object oriented style
<?php
$date = new DateTime();
echo $date->format('U = Y-m-d H:i:s') . "\n";
$date->setTimestamp(1171502725);
echo $date->format('U = Y-m-d H:i:s') . "\n";
?>
Procedural style
<?php
$date = date_create();
echo date_format($date, 'U = Y-m-d H:i:s') . "\n";
date_timestamp_set($date, 1171502725);
echo date_format($date, 'U = Y-m-d H:i:s') . "\n";
?>
The above examples will output something similar to:
1272508903 = 2010-04-28 22:41:43 1171502725 = 2007-02-14 20:25:25
Using the Unix timestamp format to construct a new DateTime object is an alternative when using PHP 5.2, as shown in the example below.
Example #2 DateTime::setTimestamp() alternative in PHP 5.2
<?php
$ts = 1171502725;
$date = new DateTime("@$ts");
echo $date->format('U = Y-m-d H:i:s') . "\n";
?>
The above example will output something similar to:
1171502725 = 2007-02-14 20:25:25
(PHP 5 >= 5.2.0, PHP 7)
DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object
Object oriented style
Procedural style
objectProcedural style only: A DateTime object returned by date_create(). The function modifies this object.
timezoneA DateTimeZone object representing the desired time zone.
Returns the DateTime object for method chaining or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.0 | Changed the
return value on success from NULL to DateTime. |
Example #1 DateTime::setTimeZone() example
Object oriented style
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
Procedural style
<?php
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
?>
The above examples will output:
2000-01-01 00:00:00+12:00 2000-01-01 01:45:00+13:45
(PHP 5 >= 5.3.0, PHP 7)
DateTime::sub -- date_sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
Object oriented style
Procedural style
Subtracts the specified DateInterval object from the specified DateTime object.
objectProcedural style only: A DateTime object returned by date_create(). The function modifies this object.
interval
A DateInterval object
Returns the DateTime object for method chaining or FALSE on failure.
Example #1 DateTime::sub() example
Object oriented style
<?php
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>
Procedural style
<?php
$date = date_create('2000-01-20');
date_sub($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>
The above examples will output:
2000-01-10
Example #2 Further DateTime::sub() examples
<?php
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>
The above example will output:
2000-01-19 13:59:30 1992-08-15 19:56:58
Example #3 Beware when subtracting months
<?php
$date = new DateTime('2001-04-30');
$interval = new DateInterval('P1M');
$date->sub($interval);
echo $date->format('Y-m-d') . "\n";
$date->sub($interval);
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-03-30 2001-03-02
DateTime::modify() is an alternative when using PHP 5.2.
(PHP 5 >= 5.5.0, PHP 7)
Representation of date and time.
$format
, string $datetime
[, DateTimeZone $timezone
] ) : DateTimeImmutable$hour
, int $minute
[, int $second = 0
[, int $microsecond = 0
]] ) : DateTimeImmutable(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::add — Adds an amount of days, months, years, hours, minutes and seconds
Like DateTime::add() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::__construct -- date_create_immutable — Returns new DateTimeImmutable object
Object oriented style
$datetime = "now"
[, DateTimeZone $timezone = NULL
]] )Procedural style
$datetime = "now"
[, DateTimeZone $timezone = NULL
]] ) : DateTimeImmutableLike DateTime::__construct() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::createFromFormat -- date_create_immutable_from_format — Parses a time string according to a specified format
Object oriented style
$format
, string $datetime
[, DateTimeZone $timezone
] ) : DateTimeImmutableProcedural style
$format
, string $datetime
[, DateTimeZone $timezone
] ) : DateTimeImmutableLike DateTime::createFromFormat() but works with DateTimeImmutable.
(PHP 5 >= 5.6.0, PHP 7)
DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable object encapsulating the given DateTime object
objectThe mutable DateTime object that you want to convert to an immutable version. This object is not modified, but instead a new DateTimeImmutable object is created containing the same date time and timezone information.
Example #1 Creating an immutable date time object
<?php
$date = new DateTime("2014-06-20 11:45 Europe/London");
$immutable = DateTimeImmutable::createFromMutable( $date );
?>
Returns a new DateTimeImmutable instance.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::getLastErrors — Returns the warnings and errors
Like DateTime::getLastErrors() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::modify — Creates a new object with modified timestamp
Creates a new DateTimeImmutable object with modified timestamp. The original object is not modified.
objectProcedural style only: A DateTime object returned by date_create(). The function modifies this object.
modifierA date/time string. Valid formats are explained in Date and Time Formats.
Returns the newly created object or FALSE on failure.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::__set_state — The __set_state handler
Like DateTime::__set_state() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::setDate — Sets the date
Like DateTime::setDate() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::setISODate — Sets the ISO date
$year
, int $week
[, int $day = 1
] ) : DateTimeImmutableLike DateTime::setISODate() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::setTime — Sets the time
$hour
, int $minute
[, int $second = 0
[, int $microsecond = 0
]] ) : DateTimeImmutableLike DateTime::setTime() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::setTimestamp — Sets the date and time based on a Unix timestamp
Like DateTime::setTimestamp() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::setTimezone — Sets the time zone
Like DateTime::setTimezone() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds
Like DateTime::sub() but works with DateTimeImmutable.
(PHP 5 >= 5.5.0, PHP 7)
DateTimeInterface is meant so that both DateTime and DateTimeImmutable can be type hinted for. It is not possible to implement this interface with userland classes.
DateTimeInterface::ATOMDATE_ATOMDATE_COOKIEDateTimeInterface::ISO8601DATE_ISO8601Note: This format is not compatible with ISO-8601, but is left this way for backward compatibility reasons. Use
DateTime::ATOMorDATE_ATOMfor compatibility with ISO-8601 instead.
DateTimeInterface::RFC822DATE_RFC822DateTimeInterface::RFC850DATE_RFC850DateTimeInterface::RFC1036DATE_RFC1036DateTimeInterface::RFC1123DATE_RFC1123DateTimeInterface::RFC7231DATE_RFC7231DateTimeInterface::RFC2822DATE_RFC2822DateTimeInterface::RFC3339DATE_RFC3339DATE_ATOM (since PHP 5.1.3)
DateTimeInterface::RFC3339_EXTENDEDDATE_RFC3339_EXTENDEDDateTimeInterface::RSSDATE_RSSDateTimeInterface::W3CDATE_W3C
| Version | Description |
|---|---|
| 7.2.0 | The class constants of DateTime are now defined on DateTimeInterface. |
| 5.5.8 | Trying to implement DateTimeInterface raises a fatal error now. Formerly implementing the interface didn't raise an error, but the behavior was erroneous. |
(PHP 5 >= 5.3.0, PHP 7)
DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diff — Returns the difference between two DateTime objects
Object oriented style
$targetObject
[, bool $absolute = FALSE
] ) : DateInterval$targetObject
[, bool $absolute = FALSE
] ) : DateInterval$targetObject
[, bool $absolute = FALSE
] ) : DateIntervalProcedural style
$originObject
, DateTimeInterface $targetObject
[, bool $absolute = FALSE
] ) : DateIntervalReturns the difference between two DateTimeInterface objects.
datetimeThe date to compare to.
absoluteShould the interval be forced to be positive?
The DateInterval object represents the
difference between the two dates or FALSE on failure.
The return value more specifically represents the interval to apply to the
original object ($this or
$originObject) to arrive at the
$targetObject. This process is not always
reversible.
Example #1 DateTime::diff() example
Object oriented style
<?php
$origin = new DateTime('2009-10-11');
$target = new DateTime('2009-10-13');
$interval = $origin->diff($target);
echo $interval->format('%R%a days');
?>
Procedural style
<?php
$origin = date_create('2009-10-11');
$target = date_create('2009-10-13');
$interval = date_diff($origin, $target);
echo $interval->format('%R%a days');
?>
The above examples will output:
+2 days
Example #2 DateTime object comparison
Note:
As of PHP 5.2.2, DateTime objects can be compared using comparison operators.
<?php
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");
var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);
?>
The above example will output:
bool(false) bool(true) bool(false)
(PHP 5 >= 5.2.1, PHP 7)
DateTime::format -- DateTimeImmutable::format -- DateTimeInterface::format -- date_format — Returns date formatted according to given format
Object oriented style
$format
) : string$format
) : string$format
) : stringProcedural style
Returns date formatted according to given format.
objectProcedural style only: A DateTime object returned by date_create()
format
The format of the outputted date string. See the formatting
options below. There are also several
predefined date constants
that may be used instead, so for example DATE_RSS
contains the format string 'D, d M Y H:i:s'.
format character |
Description | Example returned values |
|---|---|---|
| Day | --- | --- |
d |
Day of the month, 2 digits with leading zeros | 01 to 31 |
D |
A textual representation of a day, three letters | Mon through Sun |
j |
Day of the month without leading zeros | 1 to 31 |
l (lowercase 'L') |
A full textual representation of the day of the week | Sunday through Saturday |
N |
ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) | 1 (for Monday) through 7 (for Sunday) |
S |
English ordinal suffix for the day of the month, 2 characters |
st, nd, rd or
th. Works well with j
|
w |
Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
z |
The day of the year (starting from 0) | 0 through 365 |
| Week | --- | --- |
W |
ISO-8601 week number of year, weeks starting on Monday | Example: 42 (the 42nd week in the year) |
| Month | --- | --- |
F |
A full textual representation of a month, such as January or March | January through December |
m |
Numeric representation of a month, with leading zeros | 01 through 12 |
M |
A short textual representation of a month, three letters | Jan through Dec |
n |
Numeric representation of a month, without leading zeros | 1 through 12 |
t |
Number of days in the given month | 28 through 31 |
| Year | --- | --- |
L |
Whether it's a leap year | 1 if it is a leap year, 0 otherwise. |
o |
ISO-8601 week-numbering year. This has the same value as
Y, except that if the ISO week number
(W) belongs to the previous or next year, that year
is used instead. (added in PHP 5.1.0) |
Examples: 1999 or 2003 |
Y |
A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
y |
A two digit representation of a year | Examples: 99 or 03 |
| Time | --- | --- |
a |
Lowercase Ante meridiem and Post meridiem | am or pm |
A |
Uppercase Ante meridiem and Post meridiem | AM or PM |
B |
Swatch Internet time | 000 through 999 |
g |
12-hour format of an hour without leading zeros | 1 through 12 |
G |
24-hour format of an hour without leading zeros | 0 through 23 |
h |
12-hour format of an hour with leading zeros | 01 through 12 |
H |
24-hour format of an hour with leading zeros | 00 through 23 |
i |
Minutes with leading zeros | 00 to 59 |
s |
Seconds with leading zeros | 00 through 59 |
u |
Microseconds (added in PHP 5.2.2). Note that
date() will always generate
000000 since it takes an integer
parameter, whereas DateTime::format() does
support microseconds if DateTime was
created with microseconds.
|
Example: 654321 |
v |
Milliseconds (added in PHP 7.0.0). Same note applies as for
u.
|
Example: 654 |
| Timezone | --- | --- |
e |
Timezone identifier (added in PHP 5.1.0) | Examples: UTC, GMT, Atlantic/Azores |
I (capital i) |
Whether or not the date is in daylight saving time | 1 if Daylight Saving Time, 0 otherwise. |
O |
Difference to Greenwich time (GMT) without colon between hours and minutes | Example: +0200 |
P |
Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) | Example: +02:00 |
T |
Timezone abbreviation | Examples: EST, MDT ... |
Z |
Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | -43200 through 50400 |
| Full Date/Time | --- | --- |
c |
ISO 8601 date (added in PHP 5) | 2004-02-12T15:19:21+00:00 |
r |
» RFC 2822 formatted date | Example: Thu, 21 Dec 2000 16:01:07 +0200 |
U |
Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | See also time() |
Unrecognized characters in the format string will be printed
as-is. The Z format will always return
0 when using gmdate().
Note:
Since this function only accepts integer timestamps the
uformat character is only useful when using the date_format() function with user based timestamps created with date_create().
Returns the formatted date string on success or FALSE on failure.
Example #1 DateTime::format() example
Object oriented style
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Procedural style
<?php
$date = date_create('2000-01-01');
echo date_format($date, 'Y-m-d H:i:s');
?>
The above example will output:
2000-01-01 00:00:00
This method does not use locales. All output is in English.
(PHP 5 >= 5.2.1, PHP 7)
DateTime::getOffset -- DateTimeImmutable::getOffset -- DateTimeInterface::getOffset -- date_offset_get — Returns the timezone offset
Object oriented style
Procedural style
Returns the timezone offset.
objectProcedural style only: A DateTime object returned by date_create()
Returns the timezone offset in seconds from UTC on success
or FALSE on failure.
Example #1 DateTime::getOffset() example
Object oriented style
<?php
$winter = new DateTime('2010-12-21', new DateTimeZone('America/New_York'));
$summer = new DateTime('2008-06-21', new DateTimeZone('America/New_York'));
echo $winter->getOffset() . "\n";
echo $summer->getOffset() . "\n";
?>
Procedural style
<?php
$winter = date_create('2010-12-21', timezone_open('America/New_York'));
$summer = date_create('2008-06-21', timezone_open('America/New_York'));
echo date_offset_get($winter) . "\n";
echo date_offset_get($summer) . "\n";
?>
The above examples will output:
-18000 -14400
Note: -18000 = -5 hours, -14400 = -4 hours.
(PHP 5 >= 5.3.0, PHP 7)
DateTime::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTimeInterface::getTimestamp -- date_timestamp_get — Gets the Unix timestamp
Object oriented style
Procedural style
Gets the Unix timestamp.
This function has no parameters.
Returns the Unix timestamp representing the date.
Example #1 DateTime::getTimestamp() example
Object oriented style
<?php
$date = new DateTime();
echo $date->getTimestamp();
?>
Procedural style
<?php
$date = date_create();
echo date_timestamp_get($date);
?>
The above examples will output something similar to:
1272509157
Using U as the parameter to
DateTime::format()
is an alternative when using PHP 5.2.
(PHP 5 >= 5.2.1, PHP 7)
DateTime::getTimezone -- DateTimeImmutable::getTimezone -- DateTimeInterface::getTimezone -- date_timezone_get — Return time zone relative to given DateTime
Object oriented style
Procedural style
Return time zone relative to given DateTime.
objectProcedural style only: A DateTime object returned by date_create()
Returns a DateTimeZone object on success
or FALSE on failure.
Example #1 DateTime::getTimezone() example
Object oriented style
<?php
$date = new DateTime(null, new DateTimeZone('Europe/London'));
$tz = $date->getTimezone();
echo $tz->getName();
?>
Procedural style
<?php
$date = date_create(null, timezone_open('Europe/London'));
$tz = date_timezone_get($date);
echo timezone_name_get($tz);
?>
The above examples will output:
Europe/London
(PHP 5 >= 5.3.0, PHP 7)
DateTime::__wakeup -- DateTimeImmutable::__wakeup -- DateTimeInterface::__wakeup — The __wakeup handler
The __wakeup() handler.
This function has no parameters.
Initializes a DateTime object.
(PHP 5 >= 5.2.0, PHP 7)
Representation of time zone.
$timestampBegin = PHP_INT_MIN
[, int $timestampEnd = PHP_INT_MAX
]] ) : array$timezoneGroup = DateTimeZone::ALL
[, string $countryCode = NULL
]] ) : arrayDateTimeZone::AFRICAAfrica time zones.
DateTimeZone::AMERICAAmerica time zones.
DateTimeZone::ANTARCTICAAntarctica time zones.
DateTimeZone::ARCTICArctic time zones.
DateTimeZone::ASIAAsia time zones.
DateTimeZone::ATLANTICAtlantic time zones.
DateTimeZone::AUSTRALIAAustralia time zones.
DateTimeZone::EUROPEEurope time zones.
DateTimeZone::INDIANIndian time zones.
DateTimeZone::PACIFICPacific time zones.
DateTimeZone::UTCUTC time zones.
DateTimeZone::ALLAll time zones.
DateTimeZone::ALL_WITH_BCAll time zones including backwards compatible.
DateTimeZone::PER_COUNTRYTime zones per country.
(PHP 5 >= 5.2.0, PHP 7)
DateTimeZone::__construct -- timezone_open — Creates new DateTimeZone object
Object oriented style
$timezone
)Procedural style
Creates new DateTimeZone object.
Returns DateTimeZone on success.
Procedural style returns FALSE on failure.
This method throws Exception if the timezone supplied is not recognised as a valid timezone.
| Version | Description |
|---|---|
| 5.5.10 |
The timezone parameter accepts offset values.
|
Example #1 Catching errors when instantiating DateTimeZone
<?php
// Error handling by catching exceptions
$timezones = array('Europe/London', 'Mars/Phobos', 'Jupiter/Europa');
foreach ($timezones as $tz) {
try {
$mars = new DateTimeZone($tz);
} catch(Exception $e) {
echo $e->getMessage() . '<br />';
}
}
?>
The above example will output:
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos) DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)
(PHP 5 >= 5.3.0, PHP 7)
DateTimeZone::getLocation -- timezone_location_get — Returns location information for a timezone
Object oriented style
Procedural style
Returns location information for a timezone, including country code, latitude/longitude and comments.
Array containing location information about timezone or FALSE on failure.
Example #1 DateTimeZone::getLocation() example
<?php
$tz = new DateTimeZone("Europe/Prague");
print_r($tz->getLocation());
print_r(timezone_location_get($tz));
?>
The above example will output:
Array
(
[country_code] => CZ
[latitude] => 50.08333
[longitude] => 14.43333
[comments] =>
)
Array
(
[country_code] => CZ
[latitude] => 50.08333
[longitude] => 14.43333
[comments] =>
)
(PHP 5 >= 5.2.0, PHP 7)
DateTimeZone::getName -- timezone_name_get — Returns the name of the timezone
Object oriented style
Procedural style
Returns the name of the timezone.
objectThe DateTimeZone for which to get a name.
One of the timezone names in the list of timezones.
(PHP 5 >= 5.2.0, PHP 7)
DateTimeZone::getOffset -- timezone_offset_get — Returns the timezone offset from GMT
Object oriented style
Procedural style
This function returns the offset to GMT for the date/time specified in the
datetime parameter. The GMT offset is calculated
with the timezone information contained in the DateTimeZone object being used.
objectProcedural style only: A DateTimeZone object returned by timezone_open()
datetimeDateTime that contains the date/time to compute the offset from.
Returns time zone offset in seconds on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.5.19, 5.6.3 |
datetime type changed to
DateTimeInterface.
Previously, DateTime.
|
Example #1 DateTimeZone::getOffset() examples
<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");
// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now", $dateTimeZoneJapan);
// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);
// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>
(PHP 5 >= 5.2.0, PHP 7)
DateTimeZone::getTransitions -- timezone_transitions_get — Returns all transitions for the timezone
Object oriented style
$timestampBegin = PHP_INT_MIN
[, int $timestampEnd = PHP_INT_MAX
]] ) : arrayProcedural style
$object
[, int $timestampBegin = PHP_INT_MIN
[, int $timestampEnd = PHP_INT_MAX
]] ) : array
objectProcedural style only: A DateTimeZone object returned by timezone_open()
timestampBeginBegin timestamp.
timestampEndEnd timestamp.
Returns numerically indexed array containing associative array with all
transitions on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.0 |
The optional timestampBegin and timestampEnd
were added.
|
Example #1 A timezone_transitions_get() example
<?php
$timezone = new DateTimeZone("Europe/London");
$transitions = $timezone->getTransitions();
print_r(array_slice($transitions, 0, 3));
?>
The above example will output something similar to:
Array
(
[0] => Array
(
[ts] => -9223372036854775808
[time] => -292277022657-01-27T08:29:52+0000
[offset] => 3600
[isdst] => 1
[abbr] => BST
)
[1] => Array
(
[ts] => -1691964000
[time] => 1916-05-21T02:00:00+0000
[offset] => 3600
[isdst] => 1
[abbr] => BST
)
[2] => Array
(
[ts] => -1680472800
[time] => 1916-10-01T02:00:00+0000
[offset] => 0
[isdst] =>
[abbr] => GMT
)
)
(PHP 5 >= 5.2.0, PHP 7)
DateTimeZone::listAbbreviations -- timezone_abbreviations_list — Returns associative array containing dst, offset and the timezone name
Object oriented style
Procedural style
Note:
The data for this function are precompiled for performance reasons, and are not updated when using a newer » timezonedb.
Returns array on success or FALSE on failure.
Example #1 A timezone_abbreviations_list() example
<?php
$timezone_abbreviations = DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>
The above example will output something similar to:
Array
(
[0] => Array
(
[dst] => 1
[offset] => -14400
[timezone_id] => America/Porto_Acre
)
[1] => Array
(
[dst] => 1
[offset] => -14400
[timezone_id] => America/Eirunepe
)
[2] => Array
(
[dst] => 1
[offset] => -14400
[timezone_id] => America/Rio_Branco
)
[3] => Array
(
[dst] => 1
[offset] => -14400
[timezone_id] => Brazil/Acre
)
)
(PHP 5 >= 5.2.0, PHP 7)
DateTimeZone::listIdentifiers -- timezone_identifiers_list — Returns a numerically indexed array containing all defined timezone identifiers
Object oriented style
$timezoneGroup = DateTimeZone::ALL
[, string $countryCode = NULL
]] ) : arrayProcedural style
$timezoneGroup = DateTimeZone::ALL
[, string $countryCode = NULL
]] ) : array
timezoneGroupOne of the DateTimeZone class constants (or a combination).
countryCodeA two-letter ISO 3166-1 compatible country code.
Note: This option is only used when
timezoneGroupis set toDateTimeZone::PER_COUNTRY.
Returns array on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.0 |
Added the optional timezoneGroup and
countryCode parameters.
|
Example #1 A timezone_identifiers_list() example
<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
for ($i=0; $i < 5; $i++) {
echo "$timezone_identifiers[$i]\n";
}
?>
The above example will output something similar to:
Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara
(PHP 5 >= 5.3.0, PHP 7)
Represents a date interval.
A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTime's constructor supports.
More specifically, the information in an object of the DateInterval class is an instruction to get from one date/time to another date/time. This process is not always reversible.
A common way to create a DateInterval object is by calculating the difference between two date/time objects through DateTimeInterface::diff().
Number of years.
Number of months.
Number of days.
Number of hours.
Number of minutes.
Number of seconds.
Number of microseconds, as a fraction of a second.
Is 1 if the interval
represents a negative time period and
0 otherwise.
See DateInterval::format().
If the DateInterval object was created by
DateTime::diff(), then this is the total number of
days between the start and end dates. Otherwise,
days will be FALSE.
Before PHP 5.4.20/5.5.4 instead of FALSE you will receive -99999 upon
accessing the property.
| Version | Description |
|---|---|
| 7.1.0 | The f property was added. |
(PHP 5 >= 5.3.0, PHP 7)
DateInterval::__construct — Creates a new DateInterval object
$duration
)Creates a new DateInterval object.
durationAn interval specification.
The format starts with the letter P,
for period.
Each duration period is represented by an integer value
followed by a period designator.
If the duration contains time elements, that portion
of the specification is preceded by the letter
T.
| Period Designator | Description |
|---|---|
Y |
years |
M |
months |
D |
days |
W |
weeks. These get converted into days,
so can not be combined with D.
|
H |
hours |
M |
minutes |
S |
seconds |
Here are some simple examples.
Two days is P2D.
Two seconds is PT2S.
Six years and five minutes is P6YT5M.
Note:
The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as
P1Y4D, notP4D1Y.
The specification can also be represented as a date time.
A sample of one year and four days would be
P0001-00-04T00:00:00.
But the values in this format can not exceed a given period's
roll-over-point (e.g. 25 hours is invalid).
These formats are based on the » ISO 8601 duration specification.
Throws an Exception when the duration
cannot be parsed as an interval.
Example #1 DateInterval example
<?php
$interval = new DateInterval('P2Y4DT6H8M');
var_dump($interval);
?>
The above example will output:
object(DateInterval)#1 (8) {
["y"]=>
int(2)
["m"]=>
int(0)
["d"]=>
int(4)
["h"]=>
int(6)
["i"]=>
int(8)
["s"]=>
int(0)
["invert"]=>
int(0)
["days"]=>
bool(false)
}
(PHP 5 >= 5.3.0, PHP 7)
DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string.
datetimeA date with relative parts. Specifically, the relative formats supported by the parser used for strtotime() and DateTime will be used to construct the DateInterval.
Example #1 Parsing valid date intervals
<?php
// Each set of intervals is equal.
$i = new DateInterval('P1D');
$i = DateInterval::createFromDateString('1 day');
$i = new DateInterval('P2W');
$i = DateInterval::createFromDateString('2 weeks');
$i = new DateInterval('P3M');
$i = DateInterval::createFromDateString('3 months');
$i = new DateInterval('P4Y');
$i = DateInterval::createFromDateString('4 years');
$i = new DateInterval('P1Y1D');
$i = DateInterval::createFromDateString('1 year + 1 day');
$i = new DateInterval('P1DT12H');
$i = DateInterval::createFromDateString('1 day + 12 hours');
$i = new DateInterval('PT3600S');
$i = DateInterval::createFromDateString('3600 seconds');
?>
Returns a new DateInterval instance.
(PHP 5 >= 5.3.0, PHP 7)
DateInterval::format — Formats the interval
$format
) : stringFormats the interval.
format
format character |
Description | Example values |
|---|---|---|
% |
Literal % |
% |
Y |
Years, numeric, at least 2 digits with leading 0 | 01, 03 |
y |
Years, numeric | 1, 3 |
M |
Months, numeric, at least 2 digits with leading 0 | 01, 03, 12 |
m |
Months, numeric | 1, 3, 12 |
D |
Days, numeric, at least 2 digits with leading 0 | 01, 03, 31 |
d |
Days, numeric | 1, 3, 31 |
a |
Total number of days as a result of a DateTime::diff() or (unknown) otherwise |
4, 18, 8123 |
H |
Hours, numeric, at least 2 digits with leading 0 | 01, 03, 23 |
h |
Hours, numeric | 1, 3, 23 |
I |
Minutes, numeric, at least 2 digits with leading 0 | 01, 03, 59 |
i |
Minutes, numeric | 1, 3, 59 |
S |
Seconds, numeric, at least 2 digits with leading 0 | 01, 03, 57 |
s |
Seconds, numeric | 1, 3, 57 |
F |
Microseconds, numeric, at least 6 digits with leading 0 | 007701, 052738, 428291 |
f |
Microseconds, numeric | 7701, 52738, 428291 |
R |
Sign "-" when negative, "+" when positive |
-, + |
r |
Sign "-" when negative, empty when positive |
-, |
Returns the formatted interval.
Note:
The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like
"32 days"which could be interpreted as anything from"1 month and 4 days"to"1 month and 1 day".
| Version | Description |
|---|---|
| 7.1.0 | The F and f format
characters were added. |
Example #1 DateInterval example
<?php
$interval = new DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');
?>
The above example will output:
4 days
Example #2 DateInterval and carry over points
<?php
$interval = new DateInterval('P32D');
echo $interval->format('%d days');
?>
The above example will output:
32 days
Example #3 DateInterval and DateTime::diff() with the %a and %d modifiers
<?php
$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');
?>
The above example will output:
31 total days 1 month, 0 days
(PHP 5 >= 5.3.0, PHP 7)
Represents a date period.
A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.
$start
, DateInterval $interval
, int $recurrences
[, int $options
] )$start
, DateInterval $interval
, DateTimeInterface $end
[, int $options
] )DatePeriod::EXCLUDE_START_DATEExclude start date, used in DatePeriod::__construct().
The number of recurrences, if the DatePeriod instance
had been created by explicitly passing $recurrences.
See also DatePeriod::getRecurrences().
Whether to include the start date in the set of recurring dates or not.
The start date of the period.
During iteration this will contain the current date within the period.
The end date of the period.
An ISO 8601 repeating interval specification.
| Version | Description |
|---|---|
| 5.3.27, 5.4.17 | The public properties recurrences, include_start_date, start, current, end and interval have been exposed. |
(PHP 5 >= 5.3.0, PHP 7)
DatePeriod::__construct — Creates a new DatePeriod object
$start
, DateInterval $interval
, int $recurrences
[, int $options
] )$start
, DateInterval $interval
, DateTimeInterface $end
[, int $options
] )$isostr
[, int $options
] )Creates a new DatePeriod object.
startThe start date of the period.
intervalThe interval between recurrences within the period.
recurrencesThe number of recurrences.
endThe end date of the period.
isostrAn ISO 8601 repeating interval specification.
options
Can be set to DatePeriod::EXCLUDE_START_DATE to
exclude the start date from the set of recurring dates within the
period.
| Version | Description |
|---|---|
| 5.5.8 |
end type changed to
DateTimeInterface.
Previously, DateTime.
|
| 5.5.0 |
start type changed to
DateTimeInterface.
Previously, DateTime.
|
Example #1 DatePeriod example
<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');
$recurrences = 4;
$iso = 'R4/2012-07-01T00:00:00Z/P7D';
// All of these periods are equivalent.
$period = new DatePeriod($start, $interval, $recurrences);
$period = new DatePeriod($start, $interval, $end);
$period = new DatePeriod($iso);
// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
foreach ($period as $date) {
echo $date->format('Y-m-d')."\n";
}
?>
The above example will output:
2012-07-01 2012-07-08 2012-07-15 2012-07-22 2012-07-29
Example #2 DatePeriod example with DatePeriod::EXCLUDE_START_DATE
<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');
$period = new DatePeriod($start, $interval, $end,
DatePeriod::EXCLUDE_START_DATE);
// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
// Note that, in this case, 2012-07-01 is not printed.
foreach ($period as $date) {
echo $date->format('Y-m-d')."\n";
}
?>
The above example will output:
2012-07-08 2012-07-15 2012-07-22 2012-07-29
Unbound numbers of repetitions as specified by ISO 8601 section 4.5
"Recurring time interval" are not supported, i.e. neither passing
"R/..." as isostr nor passing
NULL as end would work.
(PHP 5 >= 5.6.5, PHP 7)
DatePeriod::getDateInterval — Gets the interval
Object oriented style
Gets a DateInterval object representing the interval used for the period.
This function has no parameters.
Returns a DateInterval object
Example #1 DatePeriod::getDateInterval() example
<?php
$period = new DatePeriod('R7/2016-05-16T00:00:00Z/P1D');
$interval = $period->getDateInterval();
echo $interval->format('%d day');
?>
The above example will output:
1 day
(PHP 5 >= 5.6.5, PHP 7)
DatePeriod::getEndDate — Gets the end date
Object oriented style
Gets the end date of the period.
This function has no parameters.
Returns NULL if the DatePeriod does
not have an end date. For example, when initialized with the
recurrences parameter, or the
isostr parameter without an
end date.
Returns a DateTimeImmutable object
when the DatePeriod is initialized with a
DateTimeImmutable object
as the end parameter.
Example #1 DatePeriod::getEndDate() example
<?php
$period = new DatePeriod(
new DateTime('2016-05-16T00:00:00Z'),
new DateInterval('P1D'),
new DateTime('2016-05-20T00:00:00Z')
);
$start = $period->getEndDate();
echo $start->format(DateTime::ISO8601);
?>
The above examples will output:
2016-05-20T00:00:00+0000
Example #2 DatePeriod::getEndDate() without an end date
<?php
$period = new DatePeriod(
new DateTime('2016-05-16T00:00:00Z'),
new DateInterval('P1D'),
7
);
var_dump($period->getEndDate());
?>
The above example will output:
NULL
(PHP 7 >= 7.2.17/7.3.4)
DatePeriod::getRecurrences — Gets the number of recurrences
Object oriented style
Get the number of recurrences.
This function has no parameters.
Returns the number of recurrences.
(PHP 5 >= 5.6.5, PHP 7)
DatePeriod::getStartDate — Gets the start date
Object oriented style
Gets the start date of the period.
This function has no parameters.
Returns a DateTimeImmutable object
when the DatePeriod is initialized with a
DateTimeImmutable object
as the start parameter.
Example #1 DatePeriod::getStartDate() example
<?php
$period = new DatePeriod('R7/2016-05-16T00:00:00Z/P1D');
$start = $period->getStartDate();
echo $start->format(DateTime::ISO8601);
?>
The above example will output:
2016-05-16T00:00:00+0000
(PHP 4, PHP 5, PHP 7)
checkdate — Validate a Gregorian date
$month
, int $day
, int $year
) : boolChecks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.
monthThe month is between 1 and 12 inclusive.
day
The day is within the allowed number of days for the given
month. Leap years
are taken into consideration.
yearThe year is between 1 and 32767 inclusive.
Returns TRUE if the date given is valid; otherwise returns FALSE.
Example #1 checkdate() example
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>
The above example will output:
bool(true) bool(false)
This function is an alias of: DateTime::add()
(PHP 5 >= 5.3.0, PHP 7)
date_create_from_format — Alias of DateTime::createFromFormat()
This function is an alias of: DateTime::createFromFormat()
(PHP 5 >= 5.5.0, PHP 7)
date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat()
This function is an alias of: DateTimeImmutable::createFromFormat()
(PHP 5 >= 5.5.0, PHP 7)
date_create_immutable — Alias of DateTimeImmutable::__construct()
This function is an alias of: DateTimeImmutable::__construct()
This function is an alias of: DateTime::__construct()
This function is an alias of: DateTime::setDate()
(PHP 5 >= 5.1.0, PHP 7)
date_default_timezone_get — Gets the default timezone used by all date/time functions in a script
In order of preference, this function returns the default timezone by:
Reading the timezone set using the date_default_timezone_set() function (if any)
Prior to PHP 5.4.0 only: Reading the TZ environment variable (if non empty)
Reading the value of the date.timezone ini option (if set)
Prior to PHP 5.4.0 only: Querying the host operating system (if supported and allowed by the OS). This uses an algorithm that has to guess the timezone. This is by no means going to work correctly for every situation. A warning is shown when this stage is reached. Do not rely on it to be guessed correctly, and set date.timezone to the correct timezone instead.
If none of the above succeed, date_default_timezone_get()
will return a default timezone of UTC.
Returns a string.
| Version | Description |
|---|---|
| 5.4.0 |
The TZ environment variable is no longer used to
guess the timezone.
|
| 5.4.0 | The timezone is no longer guessed from information available through the operating system as the guessed timezone can not be relied on. |
Example #1 Getting the default timezone
<?php
date_default_timezone_set('Europe/London');
if (date_default_timezone_get()) {
echo 'date_default_timezone_set: ' . date_default_timezone_get() . '<br />';
}
if (ini_get('date.timezone')) {
echo 'date.timezone: ' . ini_get('date.timezone');
}
?>
The above example will output something similar to:
date_default_timezone_set: Europe/London date.timezone: Europe/London
Example #2 Getting the abbreviation of a timezone
<?php
date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');
?>
The above example will output:
America/Los_Angeles => America/Los_Angeles => PST
(PHP 5 >= 5.1.0, PHP 7)
date_default_timezone_set — Sets the default timezone used by all date/time functions in a script
$timezoneID
) : booldate_default_timezone_set() sets the default timezone used by all date/time functions.
Note:
Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a
E_NOTICEif the timezone isn't valid, and/or aE_WARNINGmessage if using the system settings or the TZ environment variable.
Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.
timezoneID
The timezone identifier, like UTC,
Africa/Lagos, Asia/Hong_Kong, or
Europe/Lisbon. The list of valid identifiers is
available in the List of Supported Timezones.
This function returns FALSE if the
timezoneID isn't valid, or TRUE
otherwise.
Example #1 Getting the default timezone
<?php
date_default_timezone_set('America/Los_Angeles');
$script_tz = date_default_timezone_get();
if (strcmp($script_tz, ini_get('date.timezone'))){
echo 'Script timezone differs from ini-set timezone.';
} else {
echo 'Script timezone and ini-set timezone match.';
}
?>
| Version | Description |
|---|---|
| 5.3.0 |
Now throws E_WARNING rather than
E_STRICT.
|
| 5.1.2 |
The function started to validate the
timezoneID parameter.
|
This function is an alias of: DateTime::diff()
This function is an alias of: DateTime::format()
(PHP 5 >= 5.3.0, PHP 7)
date_get_last_errors — Alias of DateTime::getLastErrors()
This function is an alias of: DateTime::getLastErrors()
(PHP 5 >= 5.3.0, PHP 7)
date_interval_create_from_date_string — Alias of DateInterval::createFromDateString()
This function is an alias of: DateInterval::createFromDateString()
This function is an alias of: DateInterval::format()
This function is an alias of: DateTime::setISODate()
This function is an alias of: DateTime::modify()
This function is an alias of: DateTime::getOffset()
(PHP 5 >= 5.3.0, PHP 7)
date_parse_from_format — Get info about given date formatted according to the specified format
$format
, string $datetime
) : arrayReturns associative array with detailed info about given date/time.
formatFormat accepted by DateTime::createFromFormat().
datetimeString representing the date/time.
Returns associative array with detailed info about given date/time.
| Version | Description |
|---|---|
| 7.2.0 |
The zone element of the returned array represents
seconds instead of minutes now, and its sign is inverted. For instance
-120 is now 7200.
|
Example #1 date_parse_from_format() example
<?php
$date = "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));
?>
The above example will output:
Array
(
[year] => 2009
[month] => 1
[day] => 6
[hour] => 13
[minute] => 0
[second] => 0
[fraction] =>
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] => 1
[zone_type] => 1
[zone] => 3600
[is_dst] =>
)
(PHP 5 >= 5.2.0, PHP 7)
date_parse — Returns associative array with detailed info about given date/time
$datetime
) : array
Returns array with information about the parsed date/time
on success or FALSE on failure.
In case the date/time format has an error, the element 'errors' will contains the error messages.
| Version | Description |
|---|---|
| 7.2.0 |
The zone element of the returned array represents
seconds instead of minutes now, and its sign is inverted. For instance
-120 is now 7200.
|
Example #1 A date_parse() example
<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>
The above example will output:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
Relative formats do not influence the values parsed from absolute formats, but are parsed into the "relative" element.
Example #2 date_parse() with relative formats
<?php
print_r(date_parse("2006-12-12 10:00:00.5 +1 week +1 hour"));
?>
The above example will output:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 0
[errors] => Array
(
)
[is_localtime] =>
[relative] => Array
(
[year] => 0
[month] => 0
[day] => 7
[hour] => 1
[minute] => 0
[second] => 0
)
)This function is an alias of: DateTime::sub()
(PHP 5 >= 5.1.2, PHP 7)
date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
$timestamp
, float $latitude
, float $longitude
) : array
timestampUnix timestamp.
latitudeLatitude in degrees.
longitudeLongitude in degrees.
Returns array on success or FALSE on failure.
The structure of the array is detailed in the following list:
sunrisesunsettransitcivil_twilight_beginsunrise.
civil_twilight_endsunset.
nautical_twilight_begincivil_twilight_begin.
nautical_twilight_endcivil_twilight_end.
astronomical_twilight_beginnautical_twilight_begin.
astronomical_twilight_endnautical_twilight_end.
The values of the array elements are either UNIX timestamps, FALSE if the
sun is below the respective zenith for the whole day, or TRUE if the sun is
above the respective zenith for the whole day.
| Version | Description |
|---|---|
| 5.2.2 |
The order of latitude and
longitude has been swapped.
|
Example #1 A date_sun_info() example
<?php
$sun_info = date_sun_info(strtotime("2006-12-12"), 31.7667, 35.2333);
foreach ($sun_info as $key => $val) {
echo "$key: " . date("H:i:s", $val) . "\n";
}
?>
The above example will output:
sunrise: 05:52:11 sunset: 15:41:21 transit: 10:46:46 civil_twilight_begin: 05:24:08 civil_twilight_end: 16:09:24 nautical_twilight_begin: 04:52:25 nautical_twilight_end: 16:41:06 astronomical_twilight_begin: 04:21:32 astronomical_twilight_end: 17:12:00
Example #2 Polar night
<?php
var_dump(date_sun_info(strtotime("2017-12-21"), 90, 0));
?>
The above example will output:
array(9) {
["sunrise"]=>
bool(false)
["sunset"]=>
bool(false)
["transit"]=>
int(1513857490)
["civil_twilight_begin"]=>
bool(false)
["civil_twilight_end"]=>
bool(false)
["nautical_twilight_begin"]=>
bool(false)
["nautical_twilight_end"]=>
bool(false)
["astronomical_twilight_begin"]=>
bool(false)
["astronomical_twilight_end"]=>
bool(false)
}
Example #3 Midnight sun
<?php
var_dump(date_sun_info(strtotime("2017-06-21"), 90, 0));
?>
The above example will output:
array(9) {
["sunrise"]=>
bool(true)
["sunset"]=>
bool(true)
["transit"]=>
int(1498046510)
["civil_twilight_begin"]=>
bool(true)
["civil_twilight_end"]=>
bool(true)
["nautical_twilight_begin"]=>
bool(true)
["nautical_twilight_end"]=>
bool(true)
["astronomical_twilight_begin"]=>
bool(true)
["astronomical_twilight_end"]=>
bool(true)
}
(PHP 5, PHP 7)
date_sunrise — Returns time of sunrise for a given day and location
$timestamp
[, int $returnFormat = SUNFUNCS_RET_STRING
[, float $latitude = ini_get("date.default_latitude")
[, float $longitude = ini_get("date.default_longitude")
[, float $zenith = ini_get("date.sunrise_zenith")
[, float $utcOffset = 0
]]]]] ) : mixed
date_sunrise() returns the sunrise time for a given
day (specified as a timestamp) and location.
timestamp
The timestamp of the day from which the sunrise
time is taken.
returnFormat
| constant | description | example |
|---|---|---|
| SUNFUNCS_RET_STRING | returns the result as string | 16:46 |
| SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132 |
| SUNFUNCS_RET_TIMESTAMP | returns the result as integer (timestamp) | 1095034606 |
latitudeDefaults to North, pass in a negative value for South. See also: date.default_latitude
longitudeDefaults to East, pass in a negative value for West. See also: date.default_longitude
zenith
zenith is the angle between the center of the sun
and a line perpendicular to earth's surface. It defaults to
date.sunrise_zenith
| Angle | Description |
|---|---|
| 90°50' | Sunrise: the point where the sun becomes visible. |
| 96° | Civil twilight: conventionally used to signify the start of dawn. |
| 102° | Nautical twilight: the point at which the horizon starts being visible at sea. |
| 108° | Astronomical twilight: the point at which the sun starts being the source of any illumination. |
utcOffset
Specified in hours.
The utcOffset is ignored, if
returnFormat is
SUNFUNCS_RET_TIMESTAMP.
Returns the sunrise time in a specified returnFormat on
success or FALSE on failure. One potential reason for failure is that the
sun does not rise at all, which happens inside the polar circles for part of
the year.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT
or E_WARNING message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
| Version | Description |
|---|---|
| 5.1.0 |
Now issues the |
Example #1 date_sunrise() example
<?php
/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/
echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);
?>
The above example will output something similar to:
Mon Dec 20 2004, sunrise time : 08:54
Example #2 No sunrise
<?php
$solstice = strtotime('2017-12-21');
var_dump(date_sunrise($solstice, SUNFUNCS_RET_STRING, 69.245833, -53.537222));
?>
The above example will output:
bool(false)
(PHP 5, PHP 7)
date_sunset — Returns time of sunset for a given day and location
$timestamp
[, int $returnFormat = SUNFUNCS_RET_STRING
[, float $latitude = ini_get("date.default_latitude")
[, float $longitude = ini_get("date.default_longitude")
[, float $zenith = ini_get("date.sunset_zenith")
[, float $utcOffset = 0
]]]]] ) : mixed
date_sunset() returns the sunset time for a given
day (specified as a timestamp) and location.
timestamp
The timestamp of the day from which the sunset
time is taken.
returnFormat
| constant | description | example |
|---|---|---|
| SUNFUNCS_RET_STRING | returns the result as string | 16:46 |
| SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132 |
| SUNFUNCS_RET_TIMESTAMP | returns the result as integer (timestamp) | 1095034606 |
latitudeDefaults to North, pass in a negative value for South. See also: date.default_latitude
longitudeDefaults to East, pass in a negative value for West. See also: date.default_longitude
zenith
zenith is the angle between the center of the sun
and a line perpendicular to earth's surface. It defaults to
date.sunset_zenith
| Angle | Description |
|---|---|
| 90°50' | Sunset: the point where the sun becomes invisible. |
| 96° | Civil twilight: conventionally used to signify the end of dusk. |
| 102° | Nautical twilight: the point at which the horizon ends being visible at sea. |
| 108° | Astronomical twilight: the point at which the sun ends being the source of any illumination. |
utcOffset
Specified in hours.
The utcOffset is ignored, if
returnFormat is
SUNFUNCS_RET_TIMESTAMP.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT
or E_WARNING message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
| Version | Description |
|---|---|
| 5.1.0 |
Now issues the |
Returns the sunset time in a specified returnFormat on
success or FALSE on failure. One potential reason for failure is that the
sun does not set at all, which happens inside the polar circles for part of
the year.
Example #1 date_sunset() example
<?php
/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/
echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);
?>
The above example will output something similar to:
Mon Dec 20 2004, sunset time : 18:13
Example #2 No sunset
<?php
$solstice = strtotime('2017-12-21');
var_dump(date_sunset($solstice, SUNFUNCS_RET_STRING, 69.245833, -53.537222));
?>
The above example will output:
bool(false)
This function is an alias of: DateTime::setTime()
This function is an alias of: DateTime::getTimestamp()
This function is an alias of: DateTime::setTimestamp()
This function is an alias of: DateTime::getTimezone()
This function is an alias of: DateTime::setTimezone()
(PHP 4, PHP 5, PHP 7)
date — Format a local time/date
$format
[, int $timestamp = time()
] ) : string
Returns a string formatted according to the given format string using the
given integer timestamp or the current time
if no timestamp is given. In other words, timestamp
is optional and defaults to the value of time().
formatFormat accepted by DateTimeInterface::format().
timestamp
The optional timestamp parameter is an
integer Unix timestamp that defaults to the current
local time if a timestamp is not given. In other
words, it defaults to the value of time().
Returns a formatted date string. If a non-numeric value is used for
timestamp, FALSE is returned and an
E_WARNING level error is emitted.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT
or E_WARNING message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
| Version | Description |
|---|---|
| 5.1.1 |
There are useful constants
of standard date/time formats that can be used to specify the
format parameter.
|
| 5.1.0 | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows). |
| 5.1.0 |
Now issues the |
Example #1 date() examples
<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
// Prints something like: Monday
echo date("l");
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);
// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>
You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.
Example #2 Escaping characters in date()
<?php
// prints something like: Wednesday the 15th
echo date('l \t\h\e jS');
?>
It is possible to use date() and mktime() together to find dates in the future or the past.
Example #3 date() and mktime() example
<?php
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
?>
Note:
This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.
Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.
Example #4 date() Formatting
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>
To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().
Note:
To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's » UNIX_TIMESTAMP function).
Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.
(PHP 4, PHP 5, PHP 7)
getdate — Get date/time information
$timestamp = time()
] ) : array
Returns an associative array containing the date
information of the timestamp, or the current
local time if no timestamp is given.
Returns an associative array of information related to
the timestamp. Elements from the returned
associative array are as follows:
| Key | Description | Example returned values |
|---|---|---|
"seconds" |
Numeric representation of seconds | 0 to 59 |
"minutes" |
Numeric representation of minutes | 0 to 59 |
"hours" |
Numeric representation of hours | 0 to 23 |
"mday" |
Numeric representation of the day of the month | 1 to 31 |
"wday" |
Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
"mon" |
Numeric representation of a month | 1 through 12 |
"year" |
A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
"yday" |
Numeric representation of the day of the year | 0 through 365 |
"weekday" |
A full textual representation of the day of the week | Sunday through Saturday |
"month" |
A full textual representation of a month, such as January or March | January through December |
0 |
Seconds since the Unix Epoch, similar to the values returned by time() and used by date(). |
System Dependent, typically -2147483648 through
2147483647.
|
Example #1 getdate() example
<?php
$today = getdate();
print_r($today);
?>
The above example will output something similar to:
Array
(
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
)
(PHP 4, PHP 5, PHP 7)
gettimeofday — Get current time
This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.
returnFloat
When set to TRUE, a float instead of an array is returned.
By default an array is returned. If returnFloat
is set, then a float is returned.
Array keys:
| Version | Description |
|---|---|
| 5.1.0 |
The returnFloat parameter was added.
|
Example #1 gettimeofday() example
<?php
print_r(gettimeofday());
echo gettimeofday(true);
?>
The above example will output something similar to:
Array
(
[sec] => 1073504408
[usec] => 238215
[minuteswest] => 0
[dsttime] => 1
)
1073504408.23910
(PHP 4, PHP 5, PHP 7)
gmdate — Format a GMT/UTC date/time
$format
[, int $timestamp = time()
] ) : stringIdentical to the date() function except that the time returned is Greenwich Mean Time (GMT).
Returns a formatted date string. If a non-numeric value is used for
timestamp, FALSE is returned and an
E_WARNING level error is emitted.
| Version | Description |
|---|---|
| 5.1.1 |
There are useful constants
of standard date/time formats that can be used to specify the
format parameter.
|
| 5.1.0 | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows). |
Example #1 gmdate() example
When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00".
<?php
echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>
(PHP 4, PHP 5, PHP 7)
gmmktime — Get Unix timestamp for a GMT date
$hour = gmdate("H")
[, int $minute = gmdate("i")
[, int $second = gmdate("s")
[, int $month = gmdate("n")
[, int $day = gmdate("j")
[, int $year = gmdate("Y")
[, int $isDST = -1
]]]]]]] ) : intIdentical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.
Like mktime(), arguments may be left out in order from right to left, with any omitted arguments being set to the current corresponding GMT value.
hour
The number of the hour relative to the start of the day determined by
month, day and year.
Negative values reference the hour before midnight of the day in question.
Values greater than 23 reference the appropriate hour in the following day(s).
minute
The number of the minute relative to the start of the hour.
Negative values reference the minute in the previous hour.
Values greater than 59 reference the appropriate minute in the following hour(s).
second
The number of seconds relative to the start of the minute.
Negative values reference the second in the previous minute.
Values greater than 59 reference the appropriate second in the following minute(s).
monthThe number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s).
dayThe number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s).
yearThe year
isDST
Parameters always represent a GMT date so isDST
doesn't influence the result.
Note:
This parameter has been removed in PHP 7.0.0.
Returns a integer Unix timestamp.
| Version | Description |
|---|---|
| 7.0.0 |
isDST parameter has been removed.
|
| 5.1.0 |
As of PHP 5.1.0, the isDST parameter became
deprecated. As a result, the new timezone handling features should be used
instead.
|
Example #1 gmmktime() basic example
<?php
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", gmmktime(0, 0, 0, 7, 1, 2000));
?>
(PHP 4, PHP 5, PHP 7)
gmstrftime — Format a GMT/UTC time/date according to locale settings
$format
[, int $timestamp = time()
] ) : stringBehaves the same as strftime() except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00".
formatSee description in strftime().
timestamp
The optional timestamp parameter is an
integer Unix timestamp that defaults to the current
local time if a timestamp is not given. In other
words, it defaults to the value of time().
Returns a string formatted according to the given format string
using the given timestamp or the current
local time if no timestamp is given. Month and weekday names and
other language dependent strings respect the current locale set
with setlocale().
Example #1 gmstrftime() example
<?php
setlocale(LC_TIME, 'en_US');
echo strftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
echo gmstrftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
?>
(PHP 5, PHP 7)
idate — Format a local time/date as integer
$format
[, int $timestamp = time()
] ) : int
Returns a number formatted according to the given format string using the
given integer timestamp or the current local time
if no timestamp is given. In other words, timestamp
is optional and defaults to the value of time().
Unlike the function date(), idate()
accepts just one char in the format parameter.
format
format character |
Description |
|---|---|
B |
Swatch Beat/Internet Time |
d |
Day of the month |
h |
Hour (12 hour format) |
H |
Hour (24 hour format) |
i |
Minutes |
I (uppercase i) |
returns 1 if DST is activated,
0 otherwise |
L (uppercase l) |
returns 1 for leap year,
0 otherwise |
m |
Month number |
s |
Seconds |
t |
Days in current month |
U |
Seconds since the Unix Epoch - January 1 1970 00:00:00 UTC - this is the same as time() |
w |
Day of the week (0 on Sunday) |
W |
ISO-8601 week number of year, weeks starting on Monday |
y |
Year (1 or 2 digits - check note below) |
Y |
Year (4 digits) |
z |
Day of the year |
Z |
Timezone offset in seconds |
timestamp
The optional timestamp parameter is an
integer Unix timestamp that defaults to the current
local time if a timestamp is not given. In other
words, it defaults to the value of time().
Returns an integer.
As idate() always returns an integer and as they can't start with a "0", idate() may return fewer digits than you would expect. See the example below.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT
or E_WARNING message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
| Version | Description |
|---|---|
| 5.1.0 |
Now issues the |
Example #1 idate() example
<?php
$timestamp = strtotime('1st January 2004'); //1072915200
// this prints the year in a two digit format
// however, as this would start with a "0", it
// only prints "4"
echo idate('y', $timestamp);
?>
(PHP 4, PHP 5, PHP 7)
localtime — Get the local time
$timestamp = time()
[, bool $associative = FALSE
]] ) : arrayThe localtime() function returns an array identical to that of the structure returned by the C function call.
timestamp
The optional timestamp parameter is an
integer Unix timestamp that defaults to the current
local time if a timestamp is not given. In other
words, it defaults to the value of time().
associative
If set to FALSE or not supplied then the array is returned as a regular,
numerically indexed array. If the argument is set to TRUE then
localtime() returns an associative array containing
all the different elements of the structure returned by the C
function call to localtime. The names of the different keys of
the associative array are as follows:
0 to 59
0 to 59
0 to 23
1 to 31
0 (Jan) to 11 (Dec)
0 (Sun) to 6 (Sat)
0 to 365
0 if not, negative if unknown.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT
or E_WARNING message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
| Version | Description |
|---|---|
| 5.1.0 |
Now issues the |
Example #1 localtime() example
<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>
The above example will output something similar to:
Array
(
[0] => 24
[1] => 3
[2] => 19
[3] => 3
[4] => 3
[5] => 105
[6] => 0
[7] => 92
[8] => 1
)
Array
(
[tm_sec] => 24
[tm_min] => 3
[tm_hour] => 19
[tm_mday] => 3
[tm_mon] => 3
[tm_year] => 105
[tm_wday] => 0
[tm_yday] => 92
[tm_isdst] => 1
)
(PHP 4, PHP 5, PHP 7)
microtime — Return current Unix timestamp with microseconds
microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.
For performance measurements, using hrtime() is recommended.
By default, microtime() returns a string in
the form "msec sec", where sec is the number of seconds
since the Unix epoch (0:00:00 January 1,1970 GMT), and msec
measures microseconds that have elapsed since sec
and is also expressed in seconds.
If getAsFloat is set to TRUE, then
microtime() returns a float, which
represents the current time in seconds since the Unix epoch accurate to the
nearest microsecond.
Example #1 Timing script execution with microtime()
<?php
/**
* Simple function to replicate PHP 5 behaviour
*/
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
// Sleep for a while
usleep(100);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "Did nothing in $time seconds\n";
?>
Example #2 Timing script execution in PHP 5
<?php
$time_start = microtime(true);
// Sleep for a while
usleep(100);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did nothing in $time seconds\n";
?>
Example #3 microtime() and REQUEST_TIME_FLOAT (as of PHP 5.4.0)
<?php
// Randomize sleeping time
usleep(mt_rand(100, 10000));
// As of PHP 5.4.0, REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Did nothing in $time seconds\n";
?>
(PHP 4, PHP 5, PHP 7)
mktime — Get Unix timestamp for a date
$hour = date("H")
[, int $minute = date("i")
[, int $second = date("s")
[, int $month = date("n")
[, int $day = date("j")
[, int $year = date("Y")
[, int $isDST = -1
]]]]]]] ) : intReturns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.
Note:
As of PHP 5.1, when called with no arguments, mktime() throws an
E_STRICTnotice: use the time() function instead.
hour
The number of the hour relative to the start of the day determined by
month, day and year.
Negative values reference the hour before midnight of the day in question.
Values greater than 23 reference the appropriate hour in the following day(s).
minute
The number of the minute relative to the start of the hour.
Negative values reference the minute in the previous hour.
Values greater than 59 reference the appropriate minute in the following hour(s).
second
The number of seconds relative to the start of the minute.
Negative values reference the second in the previous minute.
Values greater than 59 reference the appropriate second in the following minute(s).
monthThe number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s).
dayThe number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s).
year
The number of the year, may be a two or four digit value,
with values between 0-69 mapping to 2000-2069 and 70-100 to
1970-2000. On systems where time_t is a 32bit signed integer, as
most common today, the valid range for year
is somewhere between 1901 and 2038. However, before PHP 5.1.0 this
range was limited from 1970 to 2038 on some systems (e.g. Windows).
isDST
This parameter can be set to 1 if the time is during daylight savings time (DST),
0 if it is not, or -1 (the default) if it is unknown whether the time is within
daylight savings time or not. If it's unknown, PHP tries to figure it out itself.
This can cause unexpected (but not incorrect) results.
Some times are invalid if DST is enabled on the system PHP is running on or
isDST is set to 1. If DST is enabled in e.g. 2:00, all times
between 2:00 and 3:00 are invalid and mktime() returns an undefined
(usually negative) value.
Some systems (e.g. Solaris 8) enable DST at midnight so time 0:30 of the day when DST
is enabled is evaluated as 23:30 of the previous day.
Note:
As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead.
Note:
This parameter has been removed in PHP 7.0.0.
mktime() returns the Unix timestamp of the arguments
given.
If the arguments are invalid, the function returns FALSE (before PHP 5.1
it returned -1).
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT
or E_WARNING message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
| Version | Description |
|---|---|
| 7.0.0 |
isDST parameter has been removed.
|
| 5.3.0 |
mktime() now throws E_DEPRECATED notice
if the isDST parameter is used.
|
| 5.1.0 |
The isDST parameter became deprecated.
Made the function return FALSE on error, instead of
-1.
Fixed the function to accept the year, month and day to be all passed
as zero.
|
| 5.1.0 |
When called with no arguments, mktime() throws
E_STRICT notice. Use the
time() function instead.
|
| 5.1.0 |
Now issues the |
Example #1 mktime() basic example
<?php
// Set the default timezone to use. Available as of PHP 5.1
date_default_timezone_set('UTC');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006));
?>
Example #2 mktime() example
mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. For example, each of the following lines produces the string "Jan-01-1998".
<?php
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));
?>
Example #3 Last day of a month
The last day of any given month can be expressed as the "0" day of the next month, not the -1 day. Both of the following examples will produce the string "The last day in Feb 2000 is: 29".
<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>
Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038.
(PHP 4, PHP 5, PHP 7)
strftime — Format a local time/date according to locale settings
$format
[, int $timestamp = time()
] ) : stringFormat the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().
Not all conversion specifiers may be supported by your C library, in which
case they will not be supported by PHP's strftime().
Additionally, not all platforms support negative timestamps, so your
date range may be limited to no earlier than the Unix epoch. This means that
%e, %T, %R and, %D (and possibly others) - as well as dates prior to
Jan 1, 1970 - will not work on Windows, some Linux
distributions, and a few other operating systems. For Windows systems, a
complete overview of supported conversion specifiers can be found at
» MSDN.
format
format |
Description | Example returned values |
|---|---|---|
| Day | --- | --- |
%a |
An abbreviated textual representation of the day | Sun through Sat |
%A |
A full textual representation of the day | Sunday through Saturday |
%d |
Two-digit day of the month (with leading zeros) | 01 to 31 |
%e |
Day of the month, with a space preceding single digits. Not implemented as described on Windows. See below for more information. | 1 to 31 |
%j |
Day of the year, 3 digits with leading zeros | 001 to 366 |
%u |
ISO-8601 numeric representation of the day of the week | 1 (for Monday) through 7 (for Sunday) |
%w |
Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
| Week | --- | --- |
%U |
Week number of the given year, starting with the first Sunday as the first week | 13 (for the 13th full week of the year) |
%V |
ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week | 01 through 53 (where 53
accounts for an overlapping week) |
%W |
A numeric representation of the week of the year, starting with the first Monday as the first week | 46 (for the 46th week of the year beginning
with a Monday) |
| Month | --- | --- |
%b |
Abbreviated month name, based on the locale | Jan through Dec |
%B |
Full month name, based on the locale | January through December |
%h |
Abbreviated month name, based on the locale (an alias of %b) | Jan through Dec |
%m |
Two digit representation of the month | 01 (for January) through 12 (for December) |
| Year | --- | --- |
%C |
Two digit representation of the century (year divided by 100, truncated to an integer) | 19 for the 20th Century |
%g |
Two digit representation of the year going by ISO-8601:1988 standards (see %V) | Example: 09 for the week of January 6, 2009 |
%G |
The full four-digit version of %g | Example: 2008 for the week of January 3, 2009 |
%y |
Two digit representation of the year | Example: 09 for 2009, 79 for 1979 |
%Y |
Four digit representation for the year | Example: 2038 |
| Time | --- | --- |
%H |
Two digit representation of the hour in 24-hour format | 00 through 23 |
%k |
Hour in 24-hour format, with a space preceding single digits | 0 through 23 |
%I |
Two digit representation of the hour in 12-hour format | 01 through 12 |
%l (lower-case 'L') |
Hour in 12-hour format, with a space preceding single digits | 1 through 12 |
%M |
Two digit representation of the minute | 00 through 59 |
%p |
UPPER-CASE 'AM' or 'PM' based on the given time | Example: AM for 00:31, PM for 22:23 |
%P |
lower-case 'am' or 'pm' based on the given time | Example: am for 00:31, pm for 22:23 |
%r |
Same as "%I:%M:%S %p" | Example: 09:34:17 PM for 21:34:17 |
%R |
Same as "%H:%M" | Example: 00:35 for 12:35 AM, 16:44 for 4:44 PM |
%S |
Two digit representation of the second | 00 through 59 |
%T |
Same as "%H:%M:%S" | Example: 21:34:17 for 09:34:17 PM |
%X |
Preferred time representation based on locale, without the date | Example: 03:59:16 or 15:59:16 |
%z |
The time zone offset. Not implemented as described on Windows. See below for more information. | Example: -0500 for US Eastern Time |
%Z |
The time zone abbreviation. Not implemented as described on Windows. See below for more information. | Example: EST for Eastern Time |
| Time and Date Stamps | --- | --- |
%c |
Preferred date and time stamp based on locale | Example: Tue Feb 5 00:45:10 2009 for
February 5, 2009 at 12:45:10 AM |
%D |
Same as "%m/%d/%y" | Example: 02/05/09 for February 5, 2009 |
%F |
Same as "%Y-%m-%d" (commonly used in database datestamps) | Example: 2009-02-05 for February 5, 2009 |
%s |
Unix Epoch Time timestamp (same as the time() function) | Example: 305815200 for September 10, 1979 08:40:00 AM |
%x |
Preferred date representation based on locale, without the time | Example: 02/05/09 for February 5, 2009 |
| Miscellaneous | --- | --- |
%n |
A newline character ("\n") | --- |
%t |
A Tab character ("\t") | --- |
%% |
A literal percentage character ("%") | --- |
Maximum length of this parameter is 1023 characters.
Contrary to ISO-9899:1999, Sun Solaris starts with Sunday as 1. As a
result, %u may not function as described in this
manual.
Windows only:
The %e modifier is not supported in the Windows
implementation of this function. To achieve this value, the
%#d modifier can be used instead. The example below
illustrates how to write a cross platform compatible function.
The %z and %Z modifiers both
return the time zone name instead of the offset or abbreviation.
macOS only: The %P modifier
is not supported in the macOS implementation of this function.
timestamp
The optional timestamp parameter is an
integer Unix timestamp that defaults to the current
local time if a timestamp is not given. In other
words, it defaults to the value of time().
Returns a string formatted according format
using the given timestamp or the current
local time if no timestamp is given. Month and weekday names and
other language-dependent strings respect the current locale set
with setlocale().
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT
or E_WARNING message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
As the output is dependent upon the underlying C library, some conversion
specifiers are not supported. On Windows, supplying unknown conversion
specifiers will result in 5 E_WARNING messages and
return FALSE. On other operating systems you may not get any
E_WARNING messages and the output may contain the
conversion specifiers unconverted.
| Version | Description |
|---|---|
| 5.1.0 |
Now issues the |
This example will work if you have the respective locales installed in your system.
Example #1 strftime() locale examples
<?php
setlocale(LC_TIME, "C");
echo strftime("%A");
setlocale(LC_TIME, "fi_FI");
echo strftime(" in Finnish is %A,");
setlocale(LC_TIME, "fr_FR");
echo strftime(" in French %A and");
setlocale(LC_TIME, "de_DE");
echo strftime(" in German %A.\n");
?>
Example #2 ISO 8601:1988 week number example
<?php
/* December 2002 / January 2003
ISOWk M Tu W Thu F Sa Su
----- ----------------------------
51 16 17 18 19 20 21 22
52 23 24 25 26 27 28 29
1 30 31 1 2 3 4 5
2 6 7 8 9 10 11 12
3 13 14 15 16 17 18 19 */
// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n";
// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n";
// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";
// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";
/* December 2004 / January 2005
ISOWk M Tu W Thu F Sa Su
----- ----------------------------
51 13 14 15 16 17 18 19
52 20 21 22 23 24 25 26
53 27 28 29 30 31 1 2
1 3 4 5 6 7 8 9
2 10 11 12 13 14 15 16 */
// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";
// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";
// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";
// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";
?>
Example #3 Cross platform compatible example using the %e modifier
<?php
// Jan 1: results in: '%e%1%' (%%, e, %%, %e, %%)
$format = '%%e%%%e%%';
// Check for Windows to find and replace the %e
// modifier correctly
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format);
}
echo strftime($format);
?>
Example #4 Display all known and unknown formats.
<?php
// Describe the formats.
$strftimeFormats = array(
'A' => 'A full textual representation of the day',
'B' => 'Full month name, based on the locale',
'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',
'D' => 'Same as "%m/%d/%y"',
'E' => '',
'F' => 'Same as "%Y-%m-%d"',
'G' => 'The full four-digit version of %g',
'H' => 'Two digit representation of the hour in 24-hour format',
'I' => 'Two digit representation of the hour in 12-hour format',
'J' => '',
'K' => '',
'L' => '',
'M' => 'Two digit representation of the minute',
'N' => '',
'O' => '',
'P' => 'lower-case "am" or "pm" based on the given time',
'Q' => '',
'R' => 'Same as "%H:%M"',
'S' => 'Two digit representation of the second',
'T' => 'Same as "%H:%M:%S"',
'U' => 'Week number of the given year, starting with the first Sunday as the first week',
'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',
'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',
'X' => 'Preferred time representation based on locale, without the date',
'Y' => 'Four digit representation for the year',
'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',
'a' => 'An abbreviated textual representation of the day',
'b' => 'Abbreviated month name, based on the locale',
'c' => 'Preferred date and time stamp based on local',
'd' => 'Two-digit day of the month (with leading zeros)',
'e' => 'Day of the month, with a space preceding single digits',
'f' => '',
'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',
'h' => 'Abbreviated month name, based on the locale (an alias of %b)',
'i' => '',
'j' => 'Day of the year, 3 digits with leading zeros',
'k' => 'Hour in 24-hour format, with a space preceding single digits',
'l' => 'Hour in 12-hour format, with a space preceding single digits',
'm' => 'Two digit representation of the month',
'n' => 'A newline character ("\n")',
'o' => '',
'p' => 'UPPER-CASE "AM" or "PM" based on the given time',
'q' => '',
'r' => 'Same as "%I:%M:%S %p"',
's' => 'Unix Epoch Time timestamp',
't' => 'A Tab character ("\t")',
'u' => 'ISO-8601 numeric representation of the day of the week',
'v' => '',
'w' => 'Numeric representation of the day of the week',
'x' => 'Preferred date representation based on locale, without the time',
'y' => 'Two digit representation of the year',
'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',
'%' => 'A literal percentage character ("%")',
);
// Results.
$strftimeValues = array();
// Evaluate the formats whilst suppressing any errors.
foreach($strftimeFormats as $format => $description){
if (False !== ($value = @strftime("%{$format}"))){
$strftimeValues[$format] = $value;
}
}
// Find the longest value.
$maxValueLength = 2 + max(array_map('strlen', $strftimeValues));
// Report known formats.
foreach($strftimeValues as $format => $value){
echo "Known format : '{$format}' = ", str_pad("'{$value}'", $maxValueLength), " ( {$strftimeFormats[$format]} )\n";
}
// Report unknown formats.
foreach(array_diff_key($strftimeFormats, $strftimeValues) as $format => $description){
echo "Unknown format : '{$format}' ", str_pad(' ', $maxValueLength), ($description ? " ( {$description} )" : ''), "\n";
}
?>
The above example will output something similar to:
Known format : 'A' = 'Friday' ( A full textual representation of the day )
Known format : 'B' = 'December' ( Full month name, based on the locale )
Known format : 'H' = '11' ( Two digit representation of the hour in 24-hour format )
Known format : 'I' = '11' ( Two digit representation of the hour in 12-hour format )
Known format : 'M' = '24' ( Two digit representation of the minute )
Known format : 'S' = '44' ( Two digit representation of the second )
Known format : 'U' = '48' ( Week number of the given year, starting with the first Sunday as the first week )
Known format : 'W' = '48' ( A numeric representation of the week of the year, starting with the first Monday as the first week )
Known format : 'X' = '11:24:44' ( Preferred time representation based on locale, without the date )
Known format : 'Y' = '2010' ( Four digit representation for the year )
Known format : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) )
Known format : 'a' = 'Fri' ( An abbreviated textual representation of the day )
Known format : 'b' = 'Dec' ( Abbreviated month name, based on the locale )
Known format : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local )
Known format : 'd' = '03' ( Two-digit day of the month (with leading zeros) )
Known format : 'j' = '337' ( Day of the year, 3 digits with leading zeros )
Known format : 'm' = '12' ( Two digit representation of the month )
Known format : 'p' = 'AM' ( UPPER-CASE "AM" or "PM" based on the given time )
Known format : 'w' = '5' ( Numeric representation of the day of the week )
Known format : 'x' = '12/03/10' ( Preferred date representation based on locale, without the time )
Known format : 'y' = '10' ( Two digit representation of the year )
Known format : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) )
Known format : '%' = '%' ( A literal percentage character ("%") )
Unknown format : 'C' ( Two digit representation of the century (year divided by 100, truncated to an integer) )
Unknown format : 'D' ( Same as "%m/%d/%y" )
Unknown format : 'E'
Unknown format : 'F' ( Same as "%Y-%m-%d" )
Unknown format : 'G' ( The full four-digit version of %g )
Unknown format : 'J'
Unknown format : 'K'
Unknown format : 'L'
Unknown format : 'N'
Unknown format : 'O'
Unknown format : 'P' ( lower-case "am" or "pm" based on the given time )
Unknown format : 'Q'
Unknown format : 'R' ( Same as "%H:%M" )
Unknown format : 'T' ( Same as "%H:%M:%S" )
Unknown format : 'V' ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week )
Unknown format : 'e' ( Day of the month, with a space preceding single digits )
Unknown format : 'f'
Unknown format : 'g' ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) )
Unknown format : 'h' ( Abbreviated month name, based on the locale (an alias of %b) )
Unknown format : 'i'
Unknown format : 'k' ( Hour in 24-hour format, with a space preceding single digits )
Unknown format : 'l' ( Hour in 12-hour format, with a space preceding single digits )
Unknown format : 'n' ( A newline character ("\n") )
Unknown format : 'o'
Unknown format : 'q'
Unknown format : 'r' ( Same as "%I:%M:%S %p" )
Unknown format : 's' ( Unix Epoch Time timestamp )
Unknown format : 't' ( A Tab character ("\t") )
Unknown format : 'u' ( ISO-8601 numeric representation of the day of the week )
Unknown format : 'v'
Note: %G and %V, which are based on ISO 8601:1988 week numbers can give unexpected (albeit correct) results if the numbering system is not thoroughly understood. See %V examples in this manual page.
$date
, string $format
) : array
strptime() returns an array with the
date parsed, or FALSE on error.
Month and weekday names and other language dependent strings respect the
current locale set with setlocale() (LC_TIME).
date (string)The string to parse (e.g. returned from strftime()).
format (string)
The format used in date (e.g. the same as
used in strftime()). Note that some of the format
options available to strftime() may not have any
effect within strptime(); the exact subset that are
supported will vary based on the operating system and C library in
use.
For more information about the format options, read the strftime() page.
Returns an array or FALSE on failure.
| parameters | Description |
|---|---|
"tm_sec" |
Seconds after the minute (0-61) |
"tm_min" |
Minutes after the hour (0-59) |
"tm_hour" |
Hour since midnight (0-23) |
"tm_mday" |
Day of the month (1-31) |
"tm_mon" |
Months since January (0-11) |
"tm_year" |
Years since 1900 |
"tm_wday" |
Days since Sunday (0-6) |
"tm_yday" |
Days since January 1 (0-365) |
"unparsed" |
the date part which was not
recognized using the specified format |
Example #1 strptime() example
<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);
echo "$strf\n";
print_r(strptime($strf, $format));
?>
The above example will output something similar to:
03/10/2004 15:54:19
Array
(
[tm_sec] => 19
[tm_min] => 54
[tm_hour] => 15
[tm_mday] => 3
[tm_mon] => 9
[tm_year] => 104
[tm_wday] => 0
[tm_yday] => 276
[unparsed] =>
)
Note: This function is not implemented on Windows platforms.
Note:
Internally, this function calls the
strptime()function provided by the system's C library. This function can exhibit noticeably different behaviour across different operating systems. The use of date_parse_from_format(), which does not suffer from these issues, is recommended on PHP 5.3.0 and later.
Note:
"tm_sec"includes any leap seconds (currently upto 2 a year). For more information on leap seconds, see the » Wikipedia article on leap seconds.
Note:
Prior to PHP 5.2.0, this function could return undefined behaviour. Notably, the
"tm_sec","tm_min"and"tm_hour"entries would return undefined values.
(PHP 4, PHP 5, PHP 7)
strtotime — Parse about any English textual datetime description into a Unix timestamp
$datetime
[, int $now = time()
] ) : int
The function expects to be given a string containing an English date format
and will try to parse that format into a Unix timestamp (the number of
seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given
in now, or the current time if
now is not supplied.
The Unix timestamp that this function returns does not contain information about time zones. In order to do calculations with date/time information, you should use the more capable DateTimeImmutable.
Each parameter of this function uses the default time zone unless a time zone is specified in that parameter. Be careful not to use different time zones in each parameter unless that is intended. See date_default_timezone_get() on the various ways to define the default time zone.
datetimeA date/time string. Valid formats are explained in Date and Time Formats.
nowThe timestamp which is used as a base for the calculation of relative dates.
Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0,
this function would return -1 on failure.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT
or E_WARNING message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
| Version | Description |
|---|---|
| 5.3.0 |
Prior to PHP 5.3.0, relative time formats supplied to the
datetime argument of strtotime()
such as this week, previous week,
last week, and next week were
interpreted to mean a 7 day period relative to the current date/time, rather
than a week period of Monday through Sunday.
|
| 5.3.0 |
Prior to PHP 5.3.0, 24:00 was not a valid format and
strtotime() returned FALSE.
|
| 5.2.7 | In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions. |
| 5.1.0 |
Now returns FALSE on failure, instead
of -1.
|
| 5.1.0 |
Now issues the |
| 5.0.2 |
In PHP 5 up to 5.0.2, "now" and other
relative times are wrongly computed from today's
midnight. This differs from other versions where it is
correctly computed from current time.
|
| 5.0.0 | Microseconds began to be allowed, but they are ignored. |
Example #1 A strtotime() example
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
Example #2 Checking for failure
<?php
$str = 'Not Good';
// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
echo "The string ($str) is bogus";
} else {
echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}
?>
Note:
If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).
Note:
The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.)
Prior to PHP 5.1.0, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems.
For 64-bit versions of PHP, the valid range of a timestamp is effectively infinite, as 64 bits can represent approximately 293 billion years in either direction.
Note:
Dates in the
m/d/yord-m-yformats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the Americanm/d/yis assumed; whereas if the separator is a dash (-) or a dot (.), then the Europeand-m-yformat is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed asy-m-d.To avoid potential ambiguity, it's best to use ISO 8601 (
YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
Note:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
(PHP 4, PHP 5, PHP 7)
time — Return current Unix timestamp
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Example #1 time() example
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60 secs
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>
The above example will output something similar to:
Now: 2005-03-30 Next Week: 2005-04-06 Next Week: 2005-04-06
Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.
(PHP 5 >= 5.2.0, PHP 7)
timezone_abbreviations_list — Alias of DateTimeZone::listAbbreviations()
This function is an alias of: DateTimeZone::listAbbreviations()
(PHP 5 >= 5.2.0, PHP 7)
timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers()
This function is an alias of: DateTimeZone::listIdentifiers()
(PHP 5 >= 5.3.0, PHP 7)
timezone_location_get — Alias of DateTimeZone::getLocation()
This function is an alias of: DateTimeZone::getLocation()
(PHP 5 >= 5.1.3, PHP 7)
timezone_name_from_abbr — Returns the timezone name from abbreviation
$abbr
[, int $utcOffset = -1
[, int $isDST = -1
]] ) : string
abbrTime zone abbreviation.
utcOffset
Offset from GMT in seconds. Defaults to -1 which means that first found
time zone corresponding to abbr is returned.
Otherwise exact offset is searched and only if not found then the first
time zone with any offset is returned.
isDST
Daylight saving time indicator. Defaults to -1, which means that
whether the time zone has daylight saving or not is not taken into
consideration when searching. If this is set to 1, then the
utcOffset is assumed to be an offset with
daylight saving in effect; if 0, then utcOffset
is assumed to be an offset without daylight saving in effect. If
abbr doesn't exist then the time zone is
searched solely by the utcOffset and
isDST.
Returns time zone name on success or FALSE on failure.
Example #1 A timezone_name_from_abbr() example
<?php
echo timezone_name_from_abbr("CET") . "\n";
echo timezone_name_from_abbr("", 3600, 0) . "\n";
?>
The above example will output something similar to:
Europe/Berlin Europe/Paris
This function is an alias of: DateTimeZone::getName()
This function is an alias of: DateTimeZone::getOffset()
This function is an alias of: DateTimeZone::__construct()
(PHP 5 >= 5.2.0, PHP 7)
timezone_transitions_get — Alias of DateTimeZone::getTransitions()
This function is an alias of: DateTimeZone::getTransitions()
(PHP 5 >= 5.3.0, PHP 7)
timezone_version_get — Gets the version of the timezonedb
Returns the current version of the timezonedb.
Returns a string.
Example #1 Getting the timezonedb version
<?php
echo timezone_version_get();
?>
The above example will output something similar to:
2009.7
This section describes all the different formats that the
DateTimeImmutable, DateTime,
date_create(),
date_create_immutable(), and
strtotime() parser understands. The formats are grouped
by section. In most cases formats from different sections, separated by
whitespace, comma or dot, can be used in the same date/time string. For each
of the supported formats, one or more examples are given, as well
as a description for the format. Characters in single quotes in
the formats are case-insensitive ('t' could
be t or T), characters in
double quotes are case-sensitive ("T" is only
T).
This page describes the different date/time formats that the DateTimeImmutable, DateTime, date_create(), date_create_immutable(), and strtotime() parser understands.
| Description | Formats | Examples |
|---|---|---|
frac |
. [0-9]+ | ".21342", ".85" |
hh |
"0"?[1-9] | "1"[0-2] | "04", "7", "12" |
HH |
[01][0-9] | "2"[0-4] | "04", "07", "19" |
meridian |
[AaPp] .? [Mm] .? [\0\t ] | "A.m.", "pM", "am." |
MM |
[0-5][0-9] | "00", "12", "59" |
II |
[0-5][0-9] | "00", "12", "59" |
space |
[ \t] | |
tz |
"("? [A-Za-z]{1,6} ")"? | [A-Z][a-z]+([_/][A-Z][a-z]+)+ | "CEST", "Europe/Amsterdam", "America/Indiana/Knox" |
tzcorrection |
"GMT"? [+-] hh ":"? MM? |
"+0400", "GMT-07:00", "-07:00" |
| Description | Format | Examples |
|---|---|---|
| Hour only, with meridian | hh space? meridian |
"4 am", "5PM" |
| Hour and minutes, with meridian | hh [.:] MM space? meridian |
"4:08 am", "7:19P.M." |
| Hour, minutes and seconds, with meridian | hh [.:] MM [.:] II space? meridian |
"4:08:37 am", "7:19:19P.M." |
| MS SQL (Hour, minutes, seconds and fraction with meridian), PHP 5.3 and later only | hh ":" MM ":" II [.:] [0-9]+ meridian |
"4:08:39:12313am" |
| Description | Format | Examples |
|---|---|---|
| Hour and minutes | 't'? HH [.:] MM |
"04:08", "19.19", "T23:43" |
| Hour and minutes, no colon | 't'? HH MM |
"0408", "t1919", "T2343" |
| Hour, minutes and seconds | 't'? HH [.:] MM [.:] II |
"04.08.37", "t19:19:19" |
| Hour, minutes and seconds, no colon | 't'? HH MM II |
"040837", "T191919" |
| Hour, minutes, seconds and timezone | 't'? HH [.:] MM [.:] II space? ( tzcorrection | tz ) |
"040837CEST", "T191919-0700" |
| Hour, minutes, seconds and fraction | 't'? HH [.:] MM [.:] II frac |
"04.08.37.81412", "19:19:19.532453" |
| Time zone information | tz | tzcorrection |
"CEST", "Europe/Amsterdam", "+0430", "GMT-06:00" |
This page describes the different date formats that the strtotime(), DateTime and date_create() parser understands.
| Description | Format | Examples |
|---|---|---|
daysuf |
"st" | "nd" | "rd" | "th" | |
dd |
([0-2]?[0-9] | "3"[01]) daysuf? |
"7th", "22nd", "31" |
DD |
"0" [0-9] | [1-2][0-9] | "3" [01] | "07", "31" |
m |
'january' | 'february' | 'march' | 'april' | 'may' | 'june' | 'july' | 'august' | 'september' | 'october' | 'november' | 'december' | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' | "I" | "II" | "III" | "IV" | "V" | "VI" | "VII" | "VIII" | "IX" | "X" | "XI" | "XII" | |
M |
'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' | |
mm |
"0"? [0-9] | "1"[0-2] | "0", "04", "7", "12" |
MM |
"0" [0-9] | "1"[0-2] | "00", "04", "07", "12" |
y |
[0-9]{1,4} | "00", "78", "08", "8", "2008" |
yy |
[0-9]{2} | "00", "08", "78" |
YY |
[0-9]{4} | "2000", "2008", "1978" |
| Description | Format | Examples |
|---|---|---|
| American month and day | mm "/" dd |
"5/12", "10/27" |
| American month, day and year | mm "/" dd "/" y |
"12/22/78", "1/17/2006", "1/17/6" |
| Four digit year, month and day with slashes | YY "/" mm "/" dd |
"2008/6/30", "1978/12/22" |
| Four digit year and month (GNU) | YY "-" mm |
"2008-6", "2008-06", "1978-12" |
| Year, month and day with dashes | y "-" mm "-" dd |
"2008-6-30", "78-12-22", "8-6-21" |
| Day, month and four digit year, with dots, tabs or dashes | dd [.\t-] mm [.-] YY |
"30-6-2008", "22.12.1978" |
| Day, month and two digit year, with dots or tabs | dd [.\t] mm "." yy |
"30.6.08", "22\t12.78" |
| Day, textual month and year | dd ([ \t.-])* m ([ \t.-])* y |
"30-June 2008", "22DEC78", "14 III 1879" |
| Textual month and four digit year (Day reset to 1) | m ([ \t.-])* YY |
"June 2008", "DEC1978", "March 1879" |
| Four digit year and textual month (Day reset to 1) | YY ([ \t.-])* m |
"2008 June", "1978-XII", "1879.MArCH" |
| Textual month, day and year | m ([ .\t-])* dd [,.stndrh\t ]+ y |
"July 1st, 2008", "April 17, 1790", "May.9,78" |
| Textual month and day | m ([ .\t-])* dd [,.stndrh\t ]* |
"July 1st,", "Apr 17", "May.9" |
| Day and textual month | d ([ .\t-])* m |
"1 July", "17 Apr", "9.May" |
| Month abbreviation, day and year | M "-" DD "-" y |
"May-09-78", "Apr-17-1790" |
| Year, month abbreviation and day | y "-" M "-" DD |
"78-Dec-22", "1814-MAY-17" |
| Year (and just the year) | YY |
"1978", "2008" |
| Textual month (and just the month) | m |
"March", "jun", "DEC" |
| Description | Format | Examples |
|---|---|---|
| Eight digit year, month and day | YY MM DD |
"15810726", "19780417", "18140517" |
| Four digit year, month and day with slashes | YY "/" MM "/" DD |
"2008/06/30", "1978/12/22" |
| Two digit year, month and day with dashes | yy "-" MM "-" DD |
"08-06-30", "78-12-22" |
| Four digit year with optional sign, month and day | [+-]? YY "-" MM "-" DD |
"-0002-07-26", "+1978-04-17", "1814-05-17" |
Note:
For the
yandyyformats, years below 100 are handled in a special way when theyoryysymbol is used. If the year falls in the range 0 (inclusive) to 69 (inclusive), 2000 is added. If the year falls in the range 70 (inclusive) to 99 (inclusive) then 1900 is added. This means that "00-01-01" is interpreted as "2000-01-01".
Note:
The "Day, month and two digit year, with dots or tabs" format (
dd[.\t]mm"."yy) only works for the year values 61 (inclusive) to 99 (inclusive) - outside those years the time format "HH[.:]MM[.:]SS" has precedence.
Note:
The "Year (and just the year)" format only works if a time string has already been found -- otherwise this format is recognised as
HHMM.
Note:
It is possible to over- and underflow the
ddandDDformat. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).Note that as of PHP 5.1.0 the day range is restricted to 0-31 as indicated by the regular expression above. Thus "2008-06-32" is not a valid date string, for instance.
It is also possible to underflow the
mmandMMformats with the value 0. A month value of 0 means December of the previous year. As example "2008-00-22" is equivalent to "2007-12-22".If you combine the previous two facts and underflow both the day and the month, the following happens: "2008-00-00" first gets converted to "2007-12-00" which then gets converted to "2007-11-30". This also happens with the string "0000-00-00", which gets transformed into "-0001-11-30" (the year -1 in the ISO 8601 calendar, which is 2 BC in the proleptic Gregorian calendar).
This page describes the different compound date/time formats that the strtotime(), DateTime and date_create() parser understands.
| Description | Formats | Examples |
|---|---|---|
DD |
"0" [0-9] | [1-2][0-9] | "3" [01] | "02", "12", "31" |
doy |
"00"[1-9] | "0"[1-9][0-9] | [1-2][0-9][0-9] | "3"[0-5][0-9] | "36"[0-6] | "001", "012", "180", "350", "366" |
frac |
. [0-9]+ | ".21342", ".85" |
hh |
"0"?[1-9] | "1"[0-2] | "04", "7", "12" |
HH |
[01][0-9] | "2"[0-4] | "04", "07", "19" |
meridian |
[AaPp] .? [Mm] .? [\0\t ] | "A.m.", "pM", "am." |
ii |
[0-5][0-9] | "04", "8", "59" |
II |
[0-5][0-9] | "04", "08", "59" |
M |
'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' | |
MM |
[0-1][0-9] | "00", "12" |
space |
[ \t] | |
ss |
[0-5][0-9] | "04", "8", "59" |
SS |
[0-5][0-9] | "04", "08", "59" |
W |
"0"[1-9] | [1-4][0-9] | "5"[0-3] | "05", "17", "53" |
tzcorrection |
"GMT"? [+-] hh ":"? II? |
"+0400", "GMT-07:00", "-07:00" |
YY |
[0-9]{4} | "2000", "2008", "1978" |
| Description | Format | Examples |
|---|---|---|
| Common Log Format | dd "/" M "/" YY : HH ":" II ":" SS space tzcorrection |
"10/Oct/2000:13:55:36 -0700" |
| EXIF | YY ":" MM ":" DD " " HH ":" II ":" SS |
"2008:08:07 18:11:31" |
| ISO year with ISO week | YY "-"? "W" W |
"2008W27", "2008-W28" |
| ISO year with ISO week and day | YY "-"? "W" W "-"? [0-7] |
"2008W273", "2008-W28-3" |
| MySQL | YY "-" MM "-" DD " " HH ":" II ":" SS |
"2008-08-07 18:11:31" |
| PostgreSQL: Year with day-of-year | YY "."? doy |
"2008.197", "2008197" |
| SOAP | YY "-" MM "-" DD "T" HH ":" II ":" SS frac tzcorrection? |
"2008-07-01T22:35:17.02", "2008-07-01T22:35:17.03+08:00" |
| Unix Timestamp | "@" "-"? [0-9]+ | "@1215282385" |
| XMLRPC | YY MM DD "T" hh ":" II ":" SS |
"20080701T22:38:07", "20080701T9:38:07" |
| XMLRPC (Compact) | YY MM DD 't' hh II SS |
"20080701t223807", "20080701T093807" |
| WDDX | YY "-" mm "-" dd "T" hh ":" ii ":" ss |
"2008-7-1T9:3:37" |
Note:
The "W" in the "ISO year with ISO week" and "ISO year with ISO week and day" formats is case-sensitive, you can only use the upper case "W".
The "T" in the SOAP, XMRPC and WDDX formats is case-sensitive, you can only use the upper case "T".
The "Unix Timestamp" format sets the timezone to UTC.
This page describes the different relative date/time formats that the strtotime(), DateTime and date_create() parser understands.
| Description | Format |
|---|---|
dayname |
'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' |
daytext |
'weekday' | 'weekdays' |
number |
[+-]?[0-9]+ |
ordinal |
'first' | 'second' | 'third' | 'fourth' | 'fifth' | 'sixth' | 'seventh' | 'eighth' | 'ninth' | 'tenth' | 'eleventh' | 'twelfth' | 'next' | 'last' | 'previous' | 'this' |
reltext |
'next' | 'last' | 'previous' | 'this' |
space |
[ \t]+ |
unit |
(('sec' | 'second' | 'min' | 'minute' | 'hour' | 'day' |
'fortnight' | 'forthnight' | 'month' | 'year') 's'?) | 'weeks' |
daytext |
| Format | Description | Examples |
|---|---|---|
| 'yesterday' | Midnight of yesterday | "yesterday 14:00" |
| 'midnight' | The time is set to 00:00:00 | |
| 'today' | The time is set to 00:00:00 | |
| 'now' | Now - this is simply ignored | |
| 'noon' | The time is set to 12:00:00 | "yesterday noon" |
| 'tomorrow' | Midnight of tomorrow | |
'back of' hour |
15 minutes past the specified hour | "back of 7pm", "back of 15" |
'front of' hour |
15 minutes before the specified hour | "front of 5am", "front of 23" |
| 'first day of' | Sets the day of the first of the current month. This phrase is best used together with a month name following it. | "first day of January 2008" |
| 'last day of' | Sets the day to the last day of the current month. This phrase is best used together with a month name following it. | "last day of next month" |
ordinal space dayname space 'of' |
Calculates the x-th week day of the current month. |
"first sat of July 2008" |
'last' space dayname space 'of' |
Calculates the last week day of the current month. | "last sat of July 2008" |
number space? (unit | 'week') |
Handles relative time items where the value is a number. | "+5 weeks", "12 day", "-7 weekdays" |
ordinal space unit |
Handles relative time items where the value is text. | "fifth day", "second month" |
| 'ago' | Negates all the values of previously found relative time items. | "2 days ago", "8 days ago 14:00", "2 months 5 days ago", "2 months ago 5 days", "2 days ago" |
dayname |
Moves to the next day of this name. | "Monday" |
reltext space 'week' |
Handles the special format "weekday + last/this/next week". | "Monday next week" |
Note:
Relative statements are always processed after non-relative statements. This makes "+1 week july 2008" and "july 2008 +1 week" equivalent.
Exceptions to this rule are: "yesterday", "midnight", "today", "noon" and "tomorrow". Note that "tomorrow 11:00" and "11:00 tomorrow" are different. Considering today's date of "July 23rd, 2008" the first one produces "2008-07-24 11:00" where as the second one produces "2008-07-24 00:00". The reason for this is that those five statements directly influence the current time.
Note:
Observe the following remarks when the current day-of-week is the same as the day-of-week used in the date/time string. The current day-of-week could have been (re-)calculated by non-relative parts of the date/time string however.
- "
dayname" does not advance to another day. (Example: "Wed July 23rd, 2008" means "2008-07-23").- "
numberdayname" does not advance to another day. (Example: "1 wednesday july 23rd, 2008" means "2008-07-23").- "
numberweekdayname" will first add the number of weeks, but does not advance to another day. In this case "numberweek" and "dayname" are two distinct blocks. (Example: "+1 week wednesday july 23rd, 2008" means "2008-07-30").- "
ordinaldayname" does advance to another day. (Example "first wednesday july 23rd, 2008" means "2008-07-30").- "
numberweekordinaldayname" will first add the number of weeks, and then advances to another day. In this case "numberweek" and "ordinaldayname" are two distinct blocks. (Example: "+1 week first wednesday july 23rd, 2008" means "2008-08-06").- "
ordinaldayname'of' " does not advance to another day. (Example: "first wednesday of july 23rd, 2008" means "2008-07-02" because the specific phrase with 'of' resets the day-of-month to '1' and the '23rd' is ignored here).Also observe that the "of" in "
ordinalspacedaynamespace'of' " and "'last'spacedaynamespace'of' " does something special.
- It sets the day-of-month to 1.
- "
ordinaldayname'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").- "
ordinaldayname" does advance to another day. (Example: "first tuesday july 2008" means "2008-07-08", see also point 4 in the list above).- "'last'
dayname'of' " takes the lastdaynameof the current month. (Example: "last wed of july 2008" means "2008-07-30")- "'last'
dayname" takes the lastdaynamefrom the current day. (Example: "last wed july 2008" means "2008-06-25"; "july 2008" first sets the current date to "2008-07-01" and then "last wed" moves to the previous Wednesday which is "2008-06-25").
Note:
Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.
Note:
numberis an integer number; if a decimal number is given, the dot (or comma) is likely interpreted as delimiter. For instance,'+1.5 hours'is parsed like'+1 5 hours', not as'+1 hour +30 minutes'.
| Version | Description |
|---|---|
| 5.6.23, 7.0.8 | Weeks always start on monday. Formerly, sunday would also be considered to start a week. |
| 5.3.3 | "first day" and "last day" changed to behave has "+1 day" and "-1 day", respectively. Previously, the behaviour was as "first day of" and "last day of". |
Here you'll find the complete list of timezones supported by PHP, which are meant to be used with e.g. date_default_timezone_set().
The behavior of timezones not listed here is undefined.
Note: The latest version of the timezone database can be installed via PECL's » timezonedb.
Note: This list is based upon the timezone database version 2020.1.
| Africa/Abidjan | Africa/Accra | Africa/Addis_Ababa | Africa/Algiers |
| Africa/Asmara | Africa/Bamako | Africa/Bangui | Africa/Banjul |
| Africa/Bissau | Africa/Blantyre | Africa/Brazzaville | Africa/Bujumbura |
| Africa/Cairo | Africa/Casablanca | Africa/Ceuta | Africa/Conakry |
| Africa/Dakar | Africa/Dar_es_Salaam | Africa/Djibouti | Africa/Douala |
| Africa/El_Aaiun | Africa/Freetown | Africa/Gaborone | Africa/Harare |
| Africa/Johannesburg | Africa/Juba | Africa/Kampala | Africa/Khartoum |
| Africa/Kigali | Africa/Kinshasa | Africa/Lagos | Africa/Libreville |
| Africa/Lome | Africa/Luanda | Africa/Lubumbashi | Africa/Lusaka |
| Africa/Malabo | Africa/Maputo | Africa/Maseru | Africa/Mbabane |
| Africa/Mogadishu | Africa/Monrovia | Africa/Nairobi | Africa/Ndjamena |
| Africa/Niamey | Africa/Nouakchott | Africa/Ouagadougou | Africa/Porto-Novo |
| Africa/Sao_Tome | Africa/Tripoli | Africa/Tunis | Africa/Windhoek |
| America/Adak | America/Anchorage | America/Anguilla | America/Antigua |
| America/Araguaina | America/Argentina/Buenos_Aires | America/Argentina/Catamarca | America/Argentina/Cordoba |
| America/Argentina/Jujuy | America/Argentina/La_Rioja | America/Argentina/Mendoza | America/Argentina/Rio_Gallegos |
| America/Argentina/Salta | America/Argentina/San_Juan | America/Argentina/San_Luis | America/Argentina/Tucuman |
| America/Argentina/Ushuaia | America/Aruba | America/Asuncion | America/Atikokan |
| America/Bahia | America/Bahia_Banderas | America/Barbados | America/Belem |
| America/Belize | America/Blanc-Sablon | America/Boa_Vista | America/Bogota |
| America/Boise | America/Cambridge_Bay | America/Campo_Grande | America/Cancun |
| America/Caracas | America/Cayenne | America/Cayman | America/Chicago |
| America/Chihuahua | America/Costa_Rica | America/Creston | America/Cuiaba |
| America/Curacao | America/Danmarkshavn | America/Dawson | America/Dawson_Creek |
| America/Denver | America/Detroit | America/Dominica | America/Edmonton |
| America/Eirunepe | America/El_Salvador | America/Fort_Nelson | America/Fortaleza |
| America/Glace_Bay | America/Goose_Bay | America/Grand_Turk | America/Grenada |
| America/Guadeloupe | America/Guatemala | America/Guayaquil | America/Guyana |
| America/Halifax | America/Havana | America/Hermosillo | America/Indiana/Indianapolis |
| America/Indiana/Knox | America/Indiana/Marengo | America/Indiana/Petersburg | America/Indiana/Tell_City |
| America/Indiana/Vevay | America/Indiana/Vincennes | America/Indiana/Winamac | America/Inuvik |
| America/Iqaluit | America/Jamaica | America/Juneau | America/Kentucky/Louisville |
| America/Kentucky/Monticello | America/Kralendijk | America/La_Paz | America/Lima |
| America/Los_Angeles | America/Lower_Princes | America/Maceio | America/Managua |
| America/Manaus | America/Marigot | America/Martinique | America/Matamoros |
| America/Mazatlan | America/Menominee | America/Merida | America/Metlakatla |
| America/Mexico_City | America/Miquelon | America/Moncton | America/Monterrey |
| America/Montevideo | America/Montserrat | America/Nassau | America/New_York |
| America/Nipigon | America/Nome | America/Noronha | America/North_Dakota/Beulah |
| America/North_Dakota/Center | America/North_Dakota/New_Salem | America/Nuuk | America/Ojinaga |
| America/Panama | America/Pangnirtung | America/Paramaribo | America/Phoenix |
| America/Port-au-Prince | America/Port_of_Spain | America/Porto_Velho | America/Puerto_Rico |
| America/Punta_Arenas | America/Rainy_River | America/Rankin_Inlet | America/Recife |
| America/Regina | America/Resolute | America/Rio_Branco | America/Santarem |
| America/Santiago | America/Santo_Domingo | America/Sao_Paulo | America/Scoresbysund |
| America/Sitka | America/St_Barthelemy | America/St_Johns | America/St_Kitts |
| America/St_Lucia | America/St_Thomas | America/St_Vincent | America/Swift_Current |
| America/Tegucigalpa | America/Thule | America/Thunder_Bay | America/Tijuana |
| America/Toronto | America/Tortola | America/Vancouver | America/Whitehorse |
| America/Winnipeg | America/Yakutat | America/Yellowknife |
| Antarctica/Casey | Antarctica/Davis | Antarctica/DumontDUrville | Antarctica/Macquarie |
| Antarctica/Mawson | Antarctica/McMurdo | Antarctica/Palmer | Antarctica/Rothera |
| Antarctica/Syowa | Antarctica/Troll | Antarctica/Vostok |
| Arctic/Longyearbyen |
| Asia/Aden | Asia/Almaty | Asia/Amman | Asia/Anadyr |
| Asia/Aqtau | Asia/Aqtobe | Asia/Ashgabat | Asia/Atyrau |
| Asia/Baghdad | Asia/Bahrain | Asia/Baku | Asia/Bangkok |
| Asia/Barnaul | Asia/Beirut | Asia/Bishkek | Asia/Brunei |
| Asia/Chita | Asia/Choibalsan | Asia/Colombo | Asia/Damascus |
| Asia/Dhaka | Asia/Dili | Asia/Dubai | Asia/Dushanbe |
| Asia/Famagusta | Asia/Gaza | Asia/Hebron | Asia/Ho_Chi_Minh |
| Asia/Hong_Kong | Asia/Hovd | Asia/Irkutsk | Asia/Jakarta |
| Asia/Jayapura | Asia/Jerusalem | Asia/Kabul | Asia/Kamchatka |
| Asia/Karachi | Asia/Kathmandu | Asia/Khandyga | Asia/Kolkata |
| Asia/Krasnoyarsk | Asia/Kuala_Lumpur | Asia/Kuching | Asia/Kuwait |
| Asia/Macau | Asia/Magadan | Asia/Makassar | Asia/Manila |
| Asia/Muscat | Asia/Nicosia | Asia/Novokuznetsk | Asia/Novosibirsk |
| Asia/Omsk | Asia/Oral | Asia/Phnom_Penh | Asia/Pontianak |
| Asia/Pyongyang | Asia/Qatar | Asia/Qostanay | Asia/Qyzylorda |
| Asia/Riyadh | Asia/Sakhalin | Asia/Samarkand | Asia/Seoul |
| Asia/Shanghai | Asia/Singapore | Asia/Srednekolymsk | Asia/Taipei |
| Asia/Tashkent | Asia/Tbilisi | Asia/Tehran | Asia/Thimphu |
| Asia/Tokyo | Asia/Tomsk | Asia/Ulaanbaatar | Asia/Urumqi |
| Asia/Ust-Nera | Asia/Vientiane | Asia/Vladivostok | Asia/Yakutsk |
| Asia/Yangon | Asia/Yekaterinburg | Asia/Yerevan |
| Atlantic/Azores | Atlantic/Bermuda | Atlantic/Canary | Atlantic/Cape_Verde |
| Atlantic/Faroe | Atlantic/Madeira | Atlantic/Reykjavik | Atlantic/South_Georgia |
| Atlantic/St_Helena | Atlantic/Stanley |
| Australia/Adelaide | Australia/Brisbane | Australia/Broken_Hill | Australia/Currie |
| Australia/Darwin | Australia/Eucla | Australia/Hobart | Australia/Lindeman |
| Australia/Lord_Howe | Australia/Melbourne | Australia/Perth | Australia/Sydney |
| Europe/Amsterdam | Europe/Andorra | Europe/Astrakhan | Europe/Athens |
| Europe/Belgrade | Europe/Berlin | Europe/Bratislava | Europe/Brussels |
| Europe/Bucharest | Europe/Budapest | Europe/Busingen | Europe/Chisinau |
| Europe/Copenhagen | Europe/Dublin | Europe/Gibraltar | Europe/Guernsey |
| Europe/Helsinki | Europe/Isle_of_Man | Europe/Istanbul | Europe/Jersey |
| Europe/Kaliningrad | Europe/Kiev | Europe/Kirov | Europe/Lisbon |
| Europe/Ljubljana | Europe/London | Europe/Luxembourg | Europe/Madrid |
| Europe/Malta | Europe/Mariehamn | Europe/Minsk | Europe/Monaco |
| Europe/Moscow | Europe/Oslo | Europe/Paris | Europe/Podgorica |
| Europe/Prague | Europe/Riga | Europe/Rome | Europe/Samara |
| Europe/San_Marino | Europe/Sarajevo | Europe/Saratov | Europe/Simferopol |
| Europe/Skopje | Europe/Sofia | Europe/Stockholm | Europe/Tallinn |
| Europe/Tirane | Europe/Ulyanovsk | Europe/Uzhgorod | Europe/Vaduz |
| Europe/Vatican | Europe/Vienna | Europe/Vilnius | Europe/Volgograd |
| Europe/Warsaw | Europe/Zagreb | Europe/Zaporozhye | Europe/Zurich |
| Indian/Antananarivo | Indian/Chagos | Indian/Christmas | Indian/Cocos |
| Indian/Comoro | Indian/Kerguelen | Indian/Mahe | Indian/Maldives |
| Indian/Mauritius | Indian/Mayotte | Indian/Reunion |
| Pacific/Apia | Pacific/Auckland | Pacific/Bougainville | Pacific/Chatham |
| Pacific/Chuuk | Pacific/Easter | Pacific/Efate | Pacific/Enderbury |
| Pacific/Fakaofo | Pacific/Fiji | Pacific/Funafuti | Pacific/Galapagos |
| Pacific/Gambier | Pacific/Guadalcanal | Pacific/Guam | Pacific/Honolulu |
| Pacific/Kiritimati | Pacific/Kosrae | Pacific/Kwajalein | Pacific/Majuro |
| Pacific/Marquesas | Pacific/Midway | Pacific/Nauru | Pacific/Niue |
| Pacific/Norfolk | Pacific/Noumea | Pacific/Pago_Pago | Pacific/Palau |
| Pacific/Pitcairn | Pacific/Pohnpei | Pacific/Port_Moresby | Pacific/Rarotonga |
| Pacific/Saipan | Pacific/Tahiti | Pacific/Tarawa | Pacific/Tongatapu |
| Pacific/Wake | Pacific/Wallis |
Please do not use any of the timezones listed here (besides UTC), they only exist for backward compatible reasons, and may expose erroneous behavior.
If you disregard the above warning, please also note that the IANA
timezone database that provides PHP's timezone support uses POSIX style
signs, which results in the Etc/GMT+n and
Etc/GMT-n time zones being reversed from common usage.
For example, the time zone 8 hours ahead of GMT that is used in China and
Western Australia (among other places) is actually
Etc/GMT-8 in this database, not
Etc/GMT+8 as you would normally expect.
Once again, it is strongly recommended that you use the correct time zone
for your location, such as Asia/Shanghai or
Australia/Perth for the above examples.
| Africa/Asmera | Africa/Timbuktu | America/Argentina/ComodRivadavia | America/Atka |
| America/Buenos_Aires | America/Catamarca | America/Coral_Harbour | America/Cordoba |
| America/Ensenada | America/Fort_Wayne | America/Godthab | America/Indianapolis |
| America/Jujuy | America/Knox_IN | America/Louisville | America/Mendoza |
| America/Montreal | America/Porto_Acre | America/Rosario | America/Santa_Isabel |
| America/Shiprock | America/Virgin | Antarctica/South_Pole | Asia/Ashkhabad |
| Asia/Calcutta | Asia/Chongqing | Asia/Chungking | Asia/Dacca |
| Asia/Harbin | Asia/Istanbul | Asia/Kashgar | Asia/Katmandu |
| Asia/Macao | Asia/Rangoon | Asia/Saigon | Asia/Tel_Aviv |
| Asia/Thimbu | Asia/Ujung_Pandang | Asia/Ulan_Bator | Atlantic/Faeroe |
| Atlantic/Jan_Mayen | Australia/ACT | Australia/Canberra | Australia/LHI |
| Australia/North | Australia/NSW | Australia/Queensland | Australia/South |
| Australia/Tasmania | Australia/Victoria | Australia/West | Australia/Yancowinna |
| Brazil/Acre | Brazil/DeNoronha | Brazil/East | Brazil/West |
| Canada/Atlantic | Canada/Central | Canada/Eastern | Canada/Mountain |
| Canada/Newfoundland | Canada/Pacific | Canada/Saskatchewan | Canada/Yukon |
| CET | Chile/Continental | Chile/EasterIsland | CST6CDT |
| Cuba | EET | Egypt | Eire |
| EST | EST5EDT | Etc/GMT | Etc/GMT+0 |
| Etc/GMT+1 | Etc/GMT+10 | Etc/GMT+11 | Etc/GMT+12 |
| Etc/GMT+2 | Etc/GMT+3 | Etc/GMT+4 | Etc/GMT+5 |
| Etc/GMT+6 | Etc/GMT+7 | Etc/GMT+8 | Etc/GMT+9 |
| Etc/GMT-0 | Etc/GMT-1 | Etc/GMT-10 | Etc/GMT-11 |
| Etc/GMT-12 | Etc/GMT-13 | Etc/GMT-14 | Etc/GMT-2 |
| Etc/GMT-3 | Etc/GMT-4 | Etc/GMT-5 | Etc/GMT-6 |
| Etc/GMT-7 | Etc/GMT-8 | Etc/GMT-9 | Etc/GMT0 |
| Etc/Greenwich | Etc/UCT | Etc/Universal | Etc/UTC |
| Etc/Zulu | Europe/Belfast | Europe/Nicosia | Europe/Tiraspol |
| Factory | GB | GB-Eire | GMT |
| GMT+0 | GMT-0 | GMT0 | Greenwich |
| Hongkong | HST | Iceland | Iran |
| Israel | Jamaica | Japan | Kwajalein |
| Libya | MET | Mexico/BajaNorte | Mexico/BajaSur |
| Mexico/General | MST | MST7MDT | Navajo |
| NZ | NZ-CHAT | Pacific/Johnston | Pacific/Ponape |
| Pacific/Samoa | Pacific/Truk | Pacific/Yap | Poland |
| Portugal | PRC | PST8PDT | ROC |
| ROK | Singapore | Turkey | UCT |
| Universal | US/Alaska | US/Aleutian | US/Arizona |
| US/Central | US/East-Indiana | US/Eastern | US/Hawaii |
| US/Indiana-Starke | US/Michigan | US/Mountain | US/Pacific |
| US/Pacific-New | US/Samoa | UTC | W-SU |
| WET | Zulu |
The HRTime extension implements a high resolution StopWatch class. It uses the best possible APIs on different platforms which brings resolution up to nanoseconds. It also makes possible to implement a custom stopwatch using low level ticks delivered by the underlaying APIs.
Note: As of PHP 7.3.0 the related function hrtime() is part of the core.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/hrtime.
A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/hrtime/.
The example illustrates the basic StopWatch class usage
Example #1 Measure several code blocks execution and get the total
<?php
$c = new HRTime\StopWatch;
$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed0 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);
/* measurement is not running here*/
for ($i = 0; $i < 1024*1024; $i++);
$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed1 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);
$elapsed_total = $c->getElapsedTime(HRTime\Unit::NANOSECOND);
?>
(PECL hrtime >= 0.4.3)
(PECL hrtime >= 0.4.3)
HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second
Returns the timer frequency in ticks per second. This value is constant after the system start on almost any operating system.
This function has no parameters.
Returns integer indicating the timer frequency.
(PECL hrtime >= 0.6.0)
HRTime\PerformanceCounter::getTicks — Current ticks from the system
Returns the ticks count.
This function has no parameters.
Returns integer indicating the ticks count.
(PECL hrtime >= 0.6.0)
HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value
$start
) : intReturns the ticks count elapsed since the given start value.
startStarting ticks value.
Returns integer indicating the ticks count.
(PECL hrtime >= 0.4.3)
(PECL hrtime >= 0.4.3)
HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals
Get elapsed ticks for all the previously closed intervals.
This function has no parameters.
Returns integer indicating elapsed ticks.
(PECL hrtime >= 0.4.3)
HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals
$unit
] ) : floatGet elapsed time for all the previously closed intervals.
unitTime unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.
Returns float indicating elapsed time.
(PECL hrtime >= 0.4.3)
HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval
Get elapsed ticks for the previously closed interval.
This function has no parameters.
Returns integer indicating elapsed ticks.
(PECL hrtime >= 0.4.3)
HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval
$unit
] ) : floatGet elapsed time for the previously closed interval.
unitTime unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.
Returns float indicating elapsed time.
(PECL hrtime >= 0.4.3)
HRTime\StopWatch::isRunning — Whether the measurement is running
Reveals whether the measurement was started.
This function has no parameters.
Returns boolean indicating whetehr the measurement is running.
(PECL hrtime >= 0.4.3)
HRTime\StopWatch::start — Start time measurement
Starts the time measurement. It has no effect if the measurement was already started. The measurement will be continued if it was previously stopped.
This function has no parameters.
Returns void.
(PECL hrtime >= 0.4.3)
HRTime\StopWatch::stop — Stop time measurement
Stop the time measurement for the previously started interval.
This function has no parameters.
Returns void.
(PECL hrtime >= 0.4.3)
HRTime\Unit::SECONDHRTime\Unit::MILLISECONDHRTime\Unit::MICROSECONDHRTime\Unit::NANOSECONDPHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.
Note:
This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.
No external libraries are needed to build this extension.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/dio.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
One resource type is defined by this extension: a file descriptor returned by dio_open().
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
F_DUPFD
(integer)
F_GETFD
(integer)
F_GETFL
(integer)
F_GETLK
(integer)
F_GETOWN
(integer)
F_RDLCK
(integer)
F_SETFL
(integer)
F_SETLK
(integer)
F_SETLKW
(integer)
F_SETOWN
(integer)
F_UNLCK
(integer)
F_WRLCK
(integer)
O_APPEND
(integer)
O_ASYNC
(integer)
O_CREAT
(integer)
O_EXCL
(integer)
O_NDELAY
(integer)
O_NOCTTY
(integer)
O_NONBLOCK
(integer)
O_RDONLY
(integer)
O_RDWR
(integer)
O_SYNC
(integer)
O_TRUNC
(integer)
O_WRONLY
(integer)
S_IRGRP
(integer)
S_IROTH
(integer)
S_IRUSR
(integer)
S_IRWXG
(integer)
S_IRWXO
(integer)
S_IRWXU
(integer)
S_IWGRP
(integer)
S_IWOTH
(integer)
S_IWUSR
(integer)
S_IXGRP
(integer)
S_IXOTH
(integer)
S_IXUSR
(integer)
(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)
dio_close — Closes the file descriptor given by fd
$fd
) : void
The function dio_close() closes the file descriptor
fd.
No value is returned.
Example #1 Closing an open file descriptor
<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);
dio_close($fd);
?>
(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)
dio_fcntl — Performs a c library fcntl on fd
The dio_fcntl() function performs the
operation specified by cmd on the file
descriptor fd. Some commands require
additional arguments args to be supplied.
fdThe file descriptor returned by dio_open().
cmdCan be one of the following operations:
F_SETLK - Lock is set or cleared. If the lock
is held by someone else dio_fcntl() returns
-1.
F_SETLKW - like F_SETLK,
but in case the lock is held by someone else,
dio_fcntl() waits until the lock is released.
F_GETLK - dio_fcntl()
returns an associative array (as described below) if someone else
prevents lock. If there is no obstruction key "type" will set
to F_UNLCK.
F_DUPFD - finds the lowest numbered available
file descriptor greater than or equal to args
and returns them.
F_SETFL - Sets the file descriptors flags to
the value specified by args, which can be
O_APPEND, O_NONBLOCK or
O_ASYNC. To use O_ASYNC
you will need to use the PCNTL
extension.
args
args is an associative array, when
cmd is F_SETLK or
F_SETLLW, with the following keys:
start - offset where lock begins
length - size of locked area. zero means to end
of file
whence - Where l_start is relative to: can be
SEEK_SET,
SEEK_END and SEEK_CUR
type - type of lock: can be
F_RDLCK (read lock),
F_WRLCK (write lock) or
F_UNLCK (unlock)
Returns the result of the C call.
Example #1 Setting and clearing a lock
<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);
if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
// the file descriptor appears locked
echo "The lock can not be cleared. It is held by someone else.";
} else {
echo "Lock successfully set/cleared";
}
dio_close($fd);
?>
Note: This function is not implemented on Windows platforms.
(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)
dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow
$filename
, int $flags
[, int $mode = 0
] ) : resourcedio_open() opens a file and returns a new file descriptor for it.
filenameThe pathname of the file to open.
flags
The flags parameter is a bitwise-ORed
value comprising flags from the following list. This value
must include one of
O_RDONLY, O_WRONLY,
or O_RDWR. Additionally, it may include
any combination of the other flags from this list.
O_RDONLY - opens the file for read access.
O_WRONLY - opens the file for write access.
O_RDWR - opens the file for both reading and
writing.
O_CREAT - creates the file, if it doesn't
already exist.
O_EXCL - if both O_CREAT
and O_EXCL are set and the file already
exists, dio_open() will fail.
O_TRUNC - if the file exists and is opened
for write access, the file will be truncated to zero length.
O_APPEND - write operations write data at the
end of the file.
O_NONBLOCK - sets non blocking mode.
O_NOCTTY - prevent the OS from
assigning the opened file as the process's controlling
terminal when opening a TTY device file.
mode
If flags contains
O_CREAT, mode will
set the permissions of the file (creation
permissions). mode is required for
correct operation when O_CREAT is
specified in flags and is ignored
otherwise.
The actual permissions assigned to the created file will be affected by the process's umask setting as per usual.
A file descriptor or FALSE on error.
Example #1 Opening a file descriptor
<?php
$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);
dio_close($fd);
?>
(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)
dio_read — Reads bytes from a file descriptor
$fd
[, int $len = 1024
] ) : string
The function dio_read() reads and returns
len bytes from file with descriptor
fd.
fdThe file descriptor returned by dio_open().
lenThe number of bytes to read. If not specified, dio_read() reads 1K sized block.
The bytes read from fd.
(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)
dio_seek — Seeks to pos on fd from whence
$fd
, int $pos
[, int $whence = SEEK_SET
] ) : intThe function dio_seek() is used to change the file position of the given file descriptor.
fdThe file descriptor returned by dio_open().
posThe new position.
whence
Specifies how the position pos should be
interpreted:
SEEK_SET (default) - specifies that
pos is specified from the beginning of the
file.
SEEK_CUR - Specifies that
pos is a count of characters from the current
file position. This count may be positive or negative.
SEEK_END - Specifies that
pos is a count of characters from the end of
the file. A negative count specifies a position within the current
extent of the file; a positive count specifies a position past the
current end. If you set the position past the current end, and
actually write data, you will extend the file with zeros up to that
position.
Example #1 Positioning in a file
<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);
dio_seek($fd, 10, SEEK_SET);
// position is now at 10 characters from the start of the file
dio_seek($fd, -2, SEEK_CUR);
// position is now at 8 characters from the start of the file
dio_seek($fd, -5, SEEK_END);
// position is now at 5 characters from the end of the file
dio_seek($fd, 10, SEEK_END);
// position is now at 10 characters past the end of the file.
// The 10 characters between the end of the file and the current
// position are filled with zeros.
dio_close($fd);
?>
(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)
dio_stat — Gets stat information about the file descriptor fd
$fd
) : arraydio_stat() returns information about the given file descriptor.
Returns an associative array with the following keys:
"device" - device
"inode" - inode
"mode" - mode
"nlink" - number of hard links
"uid" - user id
"gid" - group id
"device_type" - device type (if inode device)
"size" - total size in bytes
"blocksize" - blocksize
"blocks" - number of blocks allocated
"atime" - time of last access
"mtime" - time of last modification
"ctime" - time of last change
NULL.
(PHP 4 >= 4.3.0, PHP 5 < 5.1.0)
dio_tcsetattr — Sets terminal attributes and baud rate for a serial port
$fd
, array $options
) : bool
dio_tcsetattr() sets the terminal attributes and baud
rate of the open fd.
fdThe file descriptor returned by dio_open().
optionsThe currently available options are:
'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800, 1200,600,300,200,150,134,110,75 or 50, default value is 9600.
'bits' - data bits - can be 8,7,6 or 5. Default value is 8.
'stop' - stop bits - can be 1 or 2. Default value is 1.
'parity' - can be 0,1 or 2. Default value is 0.
No value is returned.
Example #1 Setting the baud rate on a serial port
<?php
$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);
dio_fcntl($fd, F_SETFL, O_SYNC);
dio_tcsetattr($fd, array(
'baud' => 9600,
'bits' => 8,
'stop' => 1,
'parity' => 0
));
while (1) {
$data = dio_read($fd, 256);
if ($data) {
echo $data;
}
}
?>
Note: This function is not implemented on Windows platforms.
(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)
dio_truncate — Truncates file descriptor fd to offset bytes
$fd
, int $offset
) : bool
dio_truncate() truncates a file to at most
offset bytes in size.
If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes.
Returns TRUE on success or FALSE on failure.
Note: This function is not implemented on Windows platforms.
(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)
dio_write — Writes data to fd with optional truncation at length
$fd
, string $data
[, int $len = 0
] ) : int
dio_write() writes up to len
bytes from data to file fd.
fdThe file descriptor returned by dio_open().
dataThe written data.
lenThe length of data to write in bytes. If not specified, the function writes all the data to the specified file.
Returns the number of bytes written to fd.
No external libraries are needed to build this extension.
There is no installation needed to use these functions; they are part of the PHP core.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
(PHP 4, PHP 5, PHP 7)
Instances of Directory are created by calling the dir() function, not by the new operator.
The directory that was opened.
Can be used with other directory functions such as readdir(), rewinddir() and closedir().
(PHP 4, PHP 5, PHP 7)
Directory::close — Close directory handle
$dir_handle
] ) : void
Same as closedir(), only
dir_handle defaults to $this->handle.
(PHP 4, PHP 5, PHP 7)
Directory::read — Read entry from directory handle
$dir_handle
] ) : string
Same as readdir(), only
dir_handle defaults to $this->handle.
(PHP 4, PHP 5, PHP 7)
Directory::rewind — Rewind directory handle
$dir_handle
] ) : void
Same as rewinddir(), only
dir_handle defaults to $this->handle.
For related functions such as dirname(), is_dir(), mkdir(), and rmdir(), see the Filesystem section.
(PHP 4, PHP 5, PHP 7)
chdir — Change directory
$directory
) : bool
Changes PHP's current directory to
directory.
directoryThe new current directory
Returns TRUE on success or FALSE on failure.
Throws an error of level E_WARNING on failure.
Example #1 chdir() example
<?php
// current directory
echo getcwd() . "\n";
chdir('public_html');
// current directory
echo getcwd() . "\n";
?>
The above example will output something similar to:
/home/vincent /home/vincent/public_html
Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
If the PHP interpreter has been built with ZTS (Zend Thread Safety) enabled,
any changes to the current directory made through chdir()
will be invisible to the operating system. All built-in PHP functions will
still respect the change in current directory; but external library
functions called using FFI will not. You
can tell whether your copy of PHP was built with ZTS enabled using
php -i or the built-in constant
PHP_ZTS.
(PHP 4 >= 4.0.5, PHP 5, PHP 7)
chroot — Change the root directory
$directory
) : bool
Changes the root directory of the current process to
directory, and changes the current
working directory to "/".
This function is only available to GNU and BSD systems, and only when using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.
directoryThe path to change the root directory to.
Returns TRUE on success or FALSE on failure.
Example #1 chroot() example
<?php
chroot("/path/to/your/chroot/");
echo getcwd();
?>
The above example will output:
/
Note: This function is not implemented on Windows platforms.
Note: This function is not available in PHP interpreters built with ZTS (Zend Thread Safety) enabled. To check whether your copy of PHP was built with ZTS enabled, use php -i or test the built-in constant
PHP_ZTS.
(PHP 4, PHP 5, PHP 7)
closedir — Close directory handle
$dir_handle
] ) : void
Closes the directory stream indicated by
dir_handle. The stream must have previously
been opened by opendir().
Example #1 closedir() example
<?php
$dir = "/etc/php5/";
// Open a known directory, read directory into variable and then close
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
$directory = readdir($dh);
closedir($dh);
}
}
?>
(PHP 4, PHP 5, PHP 7)
dir — Return an instance of the Directory class
A pseudo-object oriented mechanism for reading a directory. The
given directory is opened.
directoryDirectory to open
context
Note: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Returns an instance of Directory, or NULL with
wrong parameters, or FALSE in case of another error.
Example #1 dir() example
Please note the fashion in which Directory::read()'s
return value is checked in the example below. We are explicitly
testing whether the return value is identical to (equal to and of
the same type as - see
Comparison Operators for more information) FALSE since
otherwise, any directory entry whose name evaluates to FALSE will
stop the loop.
<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>
The above example will output something similar to:
Handle: Resource id #2 Path: /etc/php5 . .. apache cgi cli
Note:
The order in which directory entries are returned by the read method is system-dependent.
(PHP 4, PHP 5, PHP 7)
getcwd — Gets the current working directory
Gets the current working directory.
Returns the current working directory on success, or FALSE on
failure.
On some Unix variants, getcwd() will return
FALSE if any one of the parent directories does not have the
readable or search mode set, even if the current directory
does. See chmod() for more information on
modes and permissions.
If the PHP interpreter has been built with ZTS (Zend Thread Safety) enabled, the current working directory returned by getcwd() may be different from that returned by operating system interfaces. External libraries (invoked through FFI) which depend on the current working directory will be affected.
Example #1 getcwd() example
<?php
// current directory
echo getcwd() . "\n";
chdir('cvs');
// current directory
echo getcwd() . "\n";
?>
The above example will output something similar to:
/home/didou /home/didou/cvs
(PHP 4, PHP 5, PHP 7)
opendir — Open directory handle
$path
[, resource $context
] ) : resourceOpens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.
pathThe directory path that is to be opened
context
For a description of the context parameter,
refer to the streams section of
the manual.
Returns a directory handle resource on success,
or FALSE on failure
Upon failure, an E_WARNING is emitted.
This may happen if path is not a valid directory,
the directory can not be opened due to permission restrictions,
or due to filesystem errors.
Example #1 opendir() example
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
The above example will output something similar to:
filename: . : filetype: dir filename: .. : filetype: dir filename: apache : filetype: dir filename: cgi : filetype: dir filename: cli : filetype: dir
(PHP 4, PHP 5, PHP 7)
readdir — Read entry from directory handle
$dir_handle
] ) : stringReturns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.
Returns the entry name on success or FALSE on failure.
This function may
return Boolean FALSE, but may also return a non-Boolean value which
evaluates to FALSE. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
Example #1 List all entries in a directory
Please note the fashion in which readdir()'s
return value is checked in the examples below. We are explicitly
testing whether the return value is identical to (equal to and of
the same type as--see Comparison
Operators for more information) FALSE since otherwise,
any directory entry whose name evaluates to FALSE will stop the
loop (e.g. a directory named "0").
<?php
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle)) {
echo "$entry\n";
}
closedir($handle);
}
?>
Example #2
List all entries in the current directory and strip out .
and ..
<?php
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
?>
(PHP 4, PHP 5, PHP 7)
rewinddir — Rewind directory handle
$dir_handle
] ) : void
Resets the directory stream indicated by
dir_handle to the beginning of the
directory.
Returns NULL on success or FALSE on failure.
(PHP 5, PHP 7)
scandir — List files and directories inside the specified path
$directory
[, int $sorting_order = SCANDIR_SORT_ASCENDING
[, resource $context
]] ) : array
Returns an array of files and directories from the
directory.
directoryThe directory that will be scanned.
sorting_order
By default, the sorted order is alphabetical in ascending order. If
the optional sorting_order is set to
SCANDIR_SORT_DESCENDING, then the sort order is
alphabetical in descending order. If it is set to
SCANDIR_SORT_NONE then the result is unsorted.
context
For a description of the context parameter,
refer to the streams section of
the manual.
Returns an array of filenames on success, or FALSE on
failure. If directory is not a directory, then
boolean FALSE is returned, and an error of level
E_WARNING is generated.
| Version | Description |
|---|---|
| 5.4.0 |
sorting_order constants
were added. Any nonzero value caused descending order in previous versions. So
for all PHP versions, use 0 for ascending order, and 1
for descending order. An option for SCANDIR_SORT_NONE behavior did not
exist prior to PHP 5.4.0.
|
Example #1 A simple scandir() example
<?php
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);
?>
The above example will output something similar to:
Array
(
[0] => .
[1] => ..
[2] => bar.php
[3] => foo.txt
[4] => somedir
)
Array
(
[0] => somedir
[1] => foo.txt
[2] => bar.php
[3] => ..
[4] => .
)
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.
Before PHP 5.3.0, the magic_open library is needed to build
this extension.
This extension is enabled by default as of PHP 5.3.0. Before this time, fileinfo was a PECL extension but is no longer maintained there. However, versions prior to 5.3+ may use the » discontinued PECL extension.
Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension.
The libmagic library is bundled with PHP, but includes PHP specific changes. A patch against libmagic named libmagic.patch is maintained and may be found within the PHP fileinfo extensions source.
| PHP Version | Updated libmagic Version | Notes |
|---|---|---|
| 5.3.2 | 5.03 | |
| 5.3.0 | 5.02 |
This extension has no configuration directives defined in php.ini.
There is one resource used in Fileinfo extension: a magic database descriptor returned by finfo_open().
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
FILEINFO_NONE
(integer)
FILEINFO_SYMLINK
(integer)
FILEINFO_MIME_TYPE
(integer)
FILEINFO_MIME_ENCODING
(integer)
FILEINFO_MIME
(integer)
FILEINFO_COMPRESS
(integer)
FILEINFO_DEVICES
(integer)
FILEINFO_CONTINUE
(integer)
FILEINFO_PRESERVE_ATIME
(integer)
FILEINFO_RAW
(integer)
\ooo octal
representation.
FILEINFO_EXTENSION
(integer)
JPEG
images, then the return value is multiple extensions separated by a forward slash e.g.:
"jpeg/jpg/jpe/jfif". For unknown types not available in the
magic.mime database, then return value is "???".
Available since PHP 7.2.0.
(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)
finfo_buffer -- finfo::buffer — Return information about a string buffer
Procedural style
$finfo
, string $string
[, int $options = FILEINFO_NONE
[, resource $context
]] ) : stringObject oriented style
$string
[, int $options = FILEINFO_NONE
[, resource $context
]] ) : stringThis function is used to get information about binary data in a string.
finfoFileinfo resource returned by finfo_open().
stringContent of a file to be checked.
optionsOne or disjunction of more Fileinfo constants.
context
Returns a textual description of the string
argument, or FALSE if an error occurred.
Example #1 A finfo_buffer() example
<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($_POST["script"]) . "\n";
?>
The above example will output something similar to:
application/x-sh; charset=us-ascii
(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo_close — Close fileinfo resource
$finfo
) : boolThis function closes the resource opened by finfo_open().
Returns TRUE on success or FALSE on failure.
(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo_file -- finfo::file — Return information about a file
Procedural style
$finfo
, string $file_name
[, int $options = FILEINFO_NONE
[, resource $context
]] ) : stringObject oriented style
$file_name
[, int $options = FILEINFO_NONE
[, resource $context
]] ) : stringThis function is used to get information about a file.
finfoFileinfo resource returned by finfo_open().
file_nameName of a file to be checked.
optionsOne or disjunction of more Fileinfo constants.
context
For a description of contexts, refer to Stream Functions.
Returns a textual description of the contents of the
file_name argument, or FALSE if an error occurred.
Example #1 A finfo_file() example
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>
The above example will output something similar to:
text/html image/gif application/vnd.ms-excel
(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo_open -- finfo::__construct — Create a new fileinfo resource
Procedural style
$options = FILEINFO_NONE
[, string $magic_file = ""
]] ) : resourceObject oriented style (constructor):
This function opens a magic database and returns its resource.
optionsOne or disjunction of more Fileinfo constants.
magic_file
Name of a magic database file, usually something like
/path/to/magic.mime. If not specified, the
MAGIC environment variable is used. If the
environment variable isn't set, then PHP's bundled magic database will
be used.
Passing NULL or an empty string will be equivalent to the default
value.
(Procedural style only)
Returns a magic database resource on success or FALSE on failure.
The expected magic database format changed in PHP 5.3.11 and 5.4.1. Due to this, the internal magic database was upgraded. This mostly effects code where an external magic database is used: reading an older magic file will now fail. Also, some textual representations of the mime types has changed, for instance for PHP would be "PHP script, ASCII text" instead of "PHP script text" returned.
Note:
Generally, using the bundled magic database (by leaving
magic_fileand theMAGICenvironment variables unset) is the best course of action unless you specifically need a custom magic database.
Example #1 Object oriented style
<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension
/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);
?>
Example #2 Procedural style
<?php
$finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension
if (!$finfo) {
echo "Opening fileinfo database failed";
exit();
}
/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo finfo_file($finfo, $filename);
/* close connection */
finfo_close($finfo);
?>
The above example will output:
text/plain; charset=us-ascii
(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo_set_flags -- finfo::set_flags — Set libmagic configuration options
Procedural style
Object oriented style
This function sets various Fileinfo options. Options can be set also directly in finfo_open() or other Fileinfo functions.
finfoFileinfo resource returned by finfo_open().
optionsOne or disjunction of more Fileinfo constants.
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
mime_content_type — Detect MIME Content-type for a file
$filename
) : stringReturns the MIME content type for a file as determined by using information from the magic.mime file.
filenamePath to the tested file.
Returns the content type in MIME format, like
text/plain or application/octet-stream,
or FALSE on failure.
Upon failure, an E_WARNING is emitted.
Example #1 mime_content_type() Example
<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?>
The above example will output:
image/gif text/plain
(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)
This class provides an object oriented interface into the fileinfo functions.
(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)
finfo::buffer — Alias of finfo_buffer()
$string
[, int $options = FILEINFO_NONE
[, resource $context
]] ) : stringThis function is an alias of: finfo_buffer()
$options = FILEINFO_NONE
[, string $magic_file = ""
]] )This function is an alias of: finfo_open()
$file_name
[, int $options = FILEINFO_NONE
[, resource $context
]] ) : stringThis function is an alias of: finfo_file()
(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
finfo::set_flags — Alias of finfo_set_flags()
$options
) : boolThis function is an alias of: finfo_set_flags()
No external libraries are needed to build this extension, but if you want
PHP to support LFS (large files) on Linux, then you need to have a recent
glibc and you need compile PHP with the following compiler flags:
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.
No external libraries are needed to build this extension.
There is no installation needed to use these functions; they are part of the PHP core.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| allow_url_fopen | "1" | PHP_INI_SYSTEM | |
| allow_url_include | "0" | PHP_INI_SYSTEM | Available since PHP 5.2.0. Deprecated as of PHP 7.4.0. |
| user_agent | NULL | PHP_INI_ALL | |
| default_socket_timeout | "60" | PHP_INI_ALL | |
| from | "" | PHP_INI_ALL | |
| auto_detect_line_endings | "0" | PHP_INI_ALL | |
| sys_temp_dir | "" | PHP_INI_SYSTEM | Available since PHP 5.5.0. |
Here's a short explanation of the configuration directives.
allow_url_fopen
boolean
This option enables the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.
allow_url_include
boolean
This option allows the use of URL-aware fopen wrappers with the following functions: include, include_once, require, require_once.
Note:
This setting requires allow_url_fopen to be on.
user_agent
string
Define the user agent for PHP to send.
default_socket_timeout
integer
Default timeout (in seconds) for socket based streams. Specifying a negative value means an infinite timeout.
from
string
The email address to be used on unauthenticated FTP connections and as the value of From header for HTTP connections, when using the ftp and http wrappers, respectively.
auto_detect_line_endings
boolean
When turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.
This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.
sys_temp_dir
string
The file system uses streams as their resource type. Streams
are documented in its own reference chapter, Streams.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
SEEK_SET
(integer)
SEEK_CUR
(integer)
SEEK_END
(integer)
LOCK_SH
(integer)
LOCK_EX
(integer)
LOCK_UN
(integer)
LOCK_NB
(integer)
GLOB_BRACE
(integer)
GLOB_ONLYDIR
(integer)
GLOB_MARK
(integer)
GLOB_NOSORT
(integer)
GLOB_NOCHECK
(integer)
GLOB_NOESCAPE
(integer)
GLOB_AVAILABLE_FLAGS
(integer)
PATHINFO_DIRNAME
(integer)
PATHINFO_BASENAME
(integer)
PATHINFO_EXTENSION
(integer)
PATHINFO_FILENAME
(integer)
FILE_USE_INCLUDE_PATH
(integer)
filename in
include_path.
FILE_NO_DEFAULT_CONTEXT
(integer)
FILE_APPEND
(integer)
FILE_IGNORE_NEW_LINES
(integer)
FILE_SKIP_EMPTY_LINES
(integer)
FILE_BINARY
(integer)
Binary mode (since PHP 5.2.7).
Note:
This constant has no effect, and is only available for
forward compatibility.
FILE_TEXT
(integer)
Text mode (since PHP 5.2.7).
Note:
This constant has no effect, and is only available for
forward compatibility.
INI_SCANNER_NORMAL
(integer)
INI_SCANNER_RAW
(integer)
INI_SCANNER_TYPED
(integer)
FNM_NOESCAPE
(integer)
FNM_PATHNAME
(integer)
FNM_PERIOD
(integer)
FNM_CASEFOLD
(integer)
For related functions, see also the Directory and Program Execution sections.
For a list and explanation of the various URL wrappers that can be used as remote files, see also Supported Protocols and Wrappers.
(PHP 4, PHP 5, PHP 7)
basename — Returns trailing name component of path
$path
[, string $suffix
] ) : stringGiven a string containing the path to a file or directory, this function will return the trailing name component.
Note:
basename() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "
..".
basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function.
pathA path.
On Windows, both slash (/) and backslash
(\) are used as directory separator character. In
other environments, it is the forward slash (/).
suffix
If the name component ends in suffix this will also
be cut off.
Returns the base name of the given path.
Example #1 basename() example
<?php
echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL;
echo "2) ".basename("/etc/sudoers.d").PHP_EOL;
echo "3) ".basename("/etc/passwd").PHP_EOL;
echo "4) ".basename("/etc/").PHP_EOL;
echo "5) ".basename(".").PHP_EOL;
echo "6) ".basename("/");
?>
The above example will output:
1) sudoers 2) sudoers.d 3) passwd 4) etc 5) . 6)
(PHP 4, PHP 5, PHP 7)
chgrp — Changes file group
Attempts to change the group of the file filename
to group.
Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.
filenamePath to the file.
groupA group name or number.
Returns TRUE on success or FALSE on failure.
Example #1 Changing a file's group
<?php
$filename = 'shared_file.txt';
$format = "%s's Group ID @ %s: %d\n";
printf($format, $filename, date('r'), filegroup($filename));
chgrp($filename, 8);
clearstatcache(); // do not cache filegroup() results
printf($format, $filename, date('r'), filegroup($filename));
?>
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
Note: On Windows, this function fails silently when applied on a regular file.
(PHP 4, PHP 5, PHP 7)
chmod — Changes file mode
$filename
, int $mode
) : bool
Attempts to change the mode of the specified file to that given in
mode.
filenamePath to the file.
mode
Note that mode is not automatically
assumed to be an octal value, so to ensure the expected operation,
you need to prefix mode with a zero (0).
Strings such as "g+w" will not work properly.
<?php
chmod("/somedir/somefile", 755); // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755); // octal; correct value of mode
?>
The mode parameter consists of three octal
number components specifying access restrictions for the owner,
the user group in which the owner is in, and to everybody else in
this order. One component can be computed by adding up the needed
permissions for that target user base. Number 1 means that you
grant execute rights, number 2 means that you make the file
writeable, number 4 means that you make the file readable. Add
up these numbers to specify needed rights. You can also read more
about modes on Unix systems with 'man 1 chmod'
and 'man 2 chmod'.
<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);
// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);
// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);
// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);
?>
Returns TRUE on success or FALSE on failure.
Note:
The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems.
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
Note:
When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits.
(PHP 4, PHP 5, PHP 7)
chown — Changes file owner
Attempts to change the owner of the file filename
to user user. Only the superuser may change the
owner of a file.
filenamePath to the file.
userA user name or number.
Returns TRUE on success or FALSE on failure.
Example #1 Simple chown() usage
<?php
// File name and username to use
$file_name= "foo.php";
$path = "/home/sites/php.net/public_html/sandbox/" . $file_name ;
$user_name = "root";
// Set the user
chown($path, $user_name);
// Check the result
$stat = stat($path);
print_r(posix_getpwuid($stat['uid']));
?>
The above example will output something similar to:
Array
(
[name] => root
[passwd] => x
[uid] => 0
[gid] => 0
[gecos] => root
[dir] => /root
[shell] => /bin/bash
)
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
Note: On Windows, this function fails silently when applied on a regular file.
(PHP 4, PHP 5, PHP 7)
clearstatcache — Clears file status cache
$clear_realpath_cache = FALSE
[, string $filename
]] ) : voidWhen you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.
You should also note that PHP doesn't cache information about non-existent
files. So, if you call file_exists() on a file that
doesn't exist, it will return FALSE until you create the file. If you
create the file, it will return TRUE even if you then delete the file.
However unlink() clears the cache automatically.
Note:
This function caches information about specific filenames, so you only need to call clearstatcache() if you are performing multiple operations on the same filename and require the information about that particular file to not be cached.
Affected functions include stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().
clear_realpath_cacheWhether to clear the realpath cache or not.
filename
Clear the realpath and the stat cache for a specific filename only; only
used if clear_realpath_cache is TRUE.
No value is returned.
| Version | Description |
|---|---|
| 5.3.0 |
Added optional clear_realpath_cache
and filename parameters.
|
Example #1 clearstatcache() example
<?php
$file = 'output_log.txt';
function get_owner($file)
{
$stat = stat($file);
$user = posix_getpwuid($stat['uid']);
return $user['name'];
}
$format = "UID @ %s: %s\n";
printf($format, date('r'), get_owner($file));
chown($file, 'ross');
printf($format, date('r'), get_owner($file));
clearstatcache();
printf($format, date('r'), get_owner($file));
?>
The above example will output something similar to:
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root UID @ Sun, 12 Oct 2008 20:48:28 +0100: root UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross
(PHP 4, PHP 5, PHP 7)
copy — Copies file
$source
, string $dest
[, resource $context
] ) : bool
Makes a copy of the file source to
dest.
If you wish to move a file, use the rename() function.
sourcePath to the source file.
dest
The destination path. If dest is a URL, the
copy operation may fail if the wrapper does not support overwriting of
existing files.
If the destination file already exists, it will be overwritten.
contextA valid context resource created with stream_context_create().
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.4 |
Changed the context parameter to actually have an effect.
Previously, any context was ignored.
|
| 5.3.0 | Added context support. |
Example #1 copy() example
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
(PHP 4, PHP 5, PHP 7)
dirname — Returns a parent directory's path
$path
[, int $levels = 1
] ) : string
Given a string containing the path of a file or directory, this function
will return the parent directory's path that is
levels up from the current directory.
Note:
dirname() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "
..".
dirname() is locale aware, so for it to see the correct directory name with multibyte character paths, the matching locale must be set using the setlocale() function.
pathA path.
On Windows, both slash (/) and backslash
(\) are used as directory separator character. In
other environments, it is the forward slash (/).
levelsThe number of parent directories to go up.
This must be an integer greater than 0.
Returns the path of a parent directory. If there are no slashes in
path, a dot ('.') is returned,
indicating the current directory. Otherwise, the returned string is
path with any trailing
/component removed.
| Version | Description |
|---|---|
| 7.0.0 |
Added the optional levels parameter.
|
Example #1 dirname() example
<?php
echo dirname("/etc/passwd") . PHP_EOL;
echo dirname("/etc/") . PHP_EOL;
echo dirname(".") . PHP_EOL;
echo dirname("C:\\") . PHP_EOL;
echo dirname("/usr/local/lib", 2);
The above example will output something similar to:
/etc / (or \ on Windows) . C:\ /usr
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
disk_free_space — Returns available space on filesystem or disk partition
$directory
) : floatGiven a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.
directoryA directory of the filesystem or disk partition.
Note:
Given a file name instead of a directory, the behaviour of the function is unspecified and may differ between operating systems and PHP versions.
Returns the number of available bytes as a float
or FALSE on failure.
Example #1 disk_free_space() example
<?php
// $df contains the number of bytes available on "/"
$df = disk_free_space("/");
// On Windows:
$df_c = disk_free_space("C:");
$df_d = disk_free_space("D:");
?>
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
disk_total_space — Returns the total size of a filesystem or disk partition
$directory
) : floatGiven a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.
directoryA directory of the filesystem or disk partition.
Returns the total number of bytes as a float
or FALSE on failure.
Example #1 disk_total_space() example
<?php
// $ds contains the total number of bytes available on "/"
$ds = disk_total_space("/");
// On Windows:
$ds = disk_total_space("C:");
$ds = disk_total_space("D:");
?>
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
This function is an alias of: disk_free_space().
(PHP 4, PHP 5, PHP 7)
fclose — Closes an open file pointer
$handle
) : bool
The file pointed to by handle is closed.
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Returns TRUE on success or FALSE on failure.
Example #1 A simple fclose() example
<?php
$handle = fopen('somefile.txt', 'r');
fclose($handle);
?>
(PHP 4, PHP 5, PHP 7)
feof — Tests for end-of-file on a file pointer
$handle
) : boolTests for end-of-file on a file pointer.
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
Returns TRUE if the file pointer is at EOF or an error occurs
(including socket timeout); otherwise returns FALSE.
If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:
Example #1 Handling timeouts with feof()
<?php
function safe_feof($fp, &$start = NULL) {
$start = microtime(true);
return feof($fp);
}
/* Assuming $fp is previously opened by fsockopen() */
$start = NULL;
$timeout = ini_get('default_socket_timeout');
while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
/* Handle */
}
?>
If the passed file pointer is not valid you may get an infinite loop, because
feof() fails to return TRUE.
Example #2 feof() example with an invalid file pointer
<?php
// if file can not be read or doesn't exist fopen function returns FALSE
$file = @fopen("no_such_file", "r");
// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}
fclose($file);
?>
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
fflush — Flushes the output to a file
$handle
) : bool
This function forces a write of all buffered output to the resource
pointed to by the file handle.
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
Returns TRUE on success or FALSE on failure.
Example #1 File write example using fflush()
<?php
$filename = 'bar.txt';
$file = fopen($filename, 'r+');
rewind($file);
fwrite($file, 'Foo');
fflush($file);
ftruncate($file, ftell($file));
fclose($file);
?>
(PHP 4, PHP 5, PHP 7)
fgetc — Gets character from file pointer
$handle
) : stringGets a character from the given file pointer.
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
Returns a string containing a single character read from the file pointed
to by handle. Returns FALSE on EOF.
This function may
return Boolean FALSE, but may also return a non-Boolean value which
evaluates to FALSE. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
Example #1 A fgetc() example
<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>
Note: This function is binary-safe.
(PHP 4, PHP 5, PHP 7)
fgetcsv — Gets line from file pointer and parse for CSV fields
$handle
[, int $length = 0
[, string $delimiter = ","
[, string $enclosure = '"'
[, string $escape = "\\"
]]]] ) : arraySimilar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.
Note:
The locale settings are taken into account by this function. If
LC_CTYPEis e.g.en_US.UTF-8, files in one-byte encodings may be read wrongly by this function.
handleA valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
length
Must be greater than the longest line (in characters) to be found in
the CSV file (allowing for trailing line-end characters). Otherwise the
line is split in chunks of length characters,
unless the split would occur inside an enclosure.
Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later) the maximum line length is not limited, which is slightly slower.
delimiter
The optional delimiter parameter sets the field delimiter (one character only).
enclosure
The optional enclosure parameter sets the field enclosure character (one character only).
escape
The optional escape parameter sets the escape character (at most one character).
An empty string ("") disables the proprietary escape mechanism.
Note: Usually an
enclosurecharacter is escaped inside a field by doubling it; however, theescapecharacter can be used as an alternative. So for the default parameter values""and\"have the same meaning. Other than allowing to escape theenclosurecharacter theescapecharacter has no special meaning; it isn't even meant to escape itself.
Returns an indexed array containing the fields read.
Note:
A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
fgetcsv() returns NULL if an invalid
handle is supplied or FALSE on other errors,
including end of file.
| Version | Description |
|---|---|
| 7.4.0 |
The escape parameter now also accepts an empty
string to disable the proprietary escape mechanism.
|
| 5.3.0 |
The escape parameter was added
|
| 5.1.0 |
The length is now optional.
Default is 0, meaning no length limit.
|
Example #1 Read and print the entire contents of a CSV file
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
(PHP 4, PHP 5, PHP 7)
fgets — Gets line from file pointer
$handle
[, int $length
] ) : stringGets a line from file pointer.
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
length
Reading ends when length - 1 bytes have been
read, or a newline (which is included in the return value), or an EOF
(whichever comes first). If no length is specified, it will keep
reading from the stream until it reaches the end of the line.
Returns a string of up to length - 1 bytes read from
the file pointed to by handle. If there is no more data
to read in the file pointer, then FALSE is returned.
If an error occurs, FALSE is returned.
Example #1 Reading a file line by line
<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
Note:
People used to the 'C' semantics of fgets() should note the difference in how
EOFis returned.
(PHP 4, PHP 5, PHP 7)
fgetss — Gets line from file pointer and strip HTML tags
This function has been DEPRECATED as of PHP 7.3.0. Relying on this function is highly discouraged.
$handle
[, int $length
[, string $allowable_tags
]] ) : stringIdentical to fgets(), except that fgetss() attempts to strip any NUL bytes, HTML and PHP tags from the text it reads. The function retains the parsing state from call to call, and as such is not equivalent to calling strip_tags() on the return value of fgets().
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
lengthLength of the data to be retrieved.
allowable_tags
You can use the optional third parameter to specify tags which should
not be stripped.
See strip_tags() for details regarding
allowable_tags.
Returns a string of up to length - 1 bytes read from
the file pointed to by handle, with all HTML and PHP
code stripped.
If an error occurs, returns FALSE.
Example #1 Reading a PHP file line-by-line
<?php
$str = <<<EOD
<html><body>
<p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents('sample.php', $str);
$handle = @fopen("sample.php", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgetss($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
The above example will output something similar to:
Welcome! Today is the of .
Text outside of the HTML block.
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
(PHP 4, PHP 5, PHP 7)
file_exists — Checks whether a file or directory exists
$filename
) : boolChecks whether a file or directory exists.
filenamePath to the file or directory.
On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.
Returns TRUE if the file or directory specified by
filename exists; FALSE otherwise.
Note:
This function will return
FALSEfor symlinks pointing to non-existing files.
This function returns FALSE for files inaccessible due to safe mode restrictions. However these
files still can be included if
they are located in safe_mode_include_dir.
Note:
The check is done using the real UID/GID instead of the effective one.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Example #1 Testing whether a file exists
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
file_get_contents — Reads entire file into a string
$filename
[, bool $use_include_path = FALSE
[, resource $context
[, int $offset = 0
[, int $maxlen
]]]] ) : string
This function is similar to file(), except that
file_get_contents() returns the file in a
string, starting at the specified offset
up to maxlen bytes. On failure,
file_get_contents() will return FALSE.
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
Note:
If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().
filenameName of the file to read.
use_include_pathNote:
The
FILE_USE_INCLUDE_PATHconstant can be used to trigger include path search. This is not possible if strict typing is enabled, sinceFILE_USE_INCLUDE_PATHis an int. UseTRUEinstead.
context
A valid context resource created with
stream_context_create(). If you don't need to use a
custom context, you can skip this parameter by NULL.
offsetThe offset where the reading starts on the original stream. Negative offsets count from the end of the stream.
Seeking (offset) is not supported with remote files.
Attempting to seek on non-local files may work with small offsets, but this
is unpredictable because it works on the buffered stream.
maxlenMaximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.
The function returns the read data or FALSE on failure.
This function may
return Boolean FALSE, but may also return a non-Boolean value which
evaluates to FALSE. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
An E_WARNING level error is generated if filename cannot be found, maxlength
is less than zero, or if seeking to the specified offset in the stream fails.
Example #1 Get and output the source of the homepage of a website
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
Example #2 Searching within the include_path
<?php
// If strict types are enabled i.e. declare(strict_types=1);
$file = file_get_contents('./people.txt', true);
// Otherwise
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
Example #3 Reading a section of a file
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>
The above example will output something similar to:
string(14) "lle Bjori Ro"
Example #4 Using stream contexts
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
| Version | Description |
|---|---|
| 7.1.0 |
Support for negative offsets has been added.
|
| 5.1.0 |
Added the offset and
maxlen parameters.
|
Note: This function is binary-safe.
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
When using SSL, Microsoft IIS
will violate the protocol by closing the connection without sending a
close_notify indicator. PHP will report this as "SSL: Fatal
Protocol Error" when you reach the end of the data. To work around this, the
value of error_reporting should be
lowered to a level that does not include warnings.
PHP can detect buggy IIS server software when you open
the stream using the https:// wrapper and will suppress the
warning. When using fsockopen() to create an
ssl:// socket, the developer is responsible for detecting
and suppressing this warning.
(PHP 5, PHP 7)
file_put_contents — Write data to a file
$filename
, mixed $data
[, int $flags = 0
[, resource $context
]] ) : intThis function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
If filename does not exist, the file is created.
Otherwise, the existing file is overwritten, unless the
FILE_APPEND flag is set.
filenamePath to the file where to write the data.
dataThe data to write. Can be either a string, an array or a stream resource.
If data is a stream resource, the
remaining buffer of that stream will be copied to the specified file.
This is similar with using stream_copy_to_stream().
You can also specify the data parameter as a single
dimension array. This is equivalent to
file_put_contents($filename, implode('', $array)).
flags
The value of flags can be any combination of
the following flags, joined with the binary OR (|)
operator.
| Flag | Description |
|---|---|
FILE_USE_INCLUDE_PATH
|
Search for filename in the include directory.
See include_path for more
information.
|
FILE_APPEND
|
If file filename already exists, append
the data to the file instead of overwriting it.
|
LOCK_EX
|
Acquire an exclusive lock on the file while proceeding to the writing. In other words, a flock() call happens between the fopen() call and the fwrite() call. This is not identical to an fopen() call with mode "x". |
contextA valid context resource created with stream_context_create().
This function returns the number of bytes that were written to the file, or
FALSE on failure.
This function may
return Boolean FALSE, but may also return a non-Boolean value which
evaluates to FALSE. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
Example #1 Simple usage example
<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Example #2 Using flags
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
| Version | Description |
|---|---|
| 5.1.0 |
Added support for LOCK_EX and the ability to pass
a stream resource to the data parameter
|
Note: This function is binary-safe.
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
(PHP 4, PHP 5, PHP 7)
file — Reads entire file into an array
$filename
[, int $flags = 0
[, resource $context
]] ) : arrayReads an entire file into an array.
Note:
You can use file_get_contents() to return the contents of a file as a string.
filenamePath to the file.
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
flags
The optional parameter flags can be one, or
more, of the following constants:
FILE_USE_INCLUDE_PATH
FILE_IGNORE_NEW_LINES
FILE_SKIP_EMPTY_LINES
contextA context resource created with the stream_context_create() function.
Note: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Returns the file in an array. Each element of the array corresponds to a
line in the file, with the newline still attached. Upon failure,
file() returns FALSE.
Note:
Each line in the resulting array will include the line ending, unless
FILE_IGNORE_NEW_LINESis used.
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
Emits an E_WARNING level error if the file
does not exist.
Example #1 file() example
<?php
// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
// Another example, let's get a web page into a string. See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
// Using the optional flags parameter since PHP 5
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>
When using SSL, Microsoft IIS
will violate the protocol by closing the connection without sending a
close_notify indicator. PHP will report this as "SSL: Fatal
Protocol Error" when you reach the end of the data. To work around this, the
value of error_reporting should be
lowered to a level that does not include warnings.
PHP can detect buggy IIS server software when you open
the stream using the https:// wrapper and will suppress the
warning. When using fsockopen() to create an
ssl:// socket, the developer is responsible for detecting
and suppressing this warning.
(PHP 4, PHP 5, PHP 7)
fileatime — Gets last access time of file
$filename
) : intGets the last access time of the given file.
filenamePath to the file.
Returns the time the file was last accessed, or FALSE on failure.
The time is returned as a Unix timestamp.
Example #1 fileatime() example
<?php
// outputs e.g. somefile.txt was last accessed: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last accessed: " . date("F d Y H:i:s.", fileatime($filename));
}
?>
Upon failure, an E_WARNING is emitted.
Note:
The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performance-wise when an application regularly accesses a very large number of files or directories.
Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such applications; USENET news spools are a common example. On such filesystems this function will be useless.
Note:
Note that time resolution may differ from one file system to another.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
filectime — Gets inode change time of file
$filename
) : intGets the inode change time of a file.
filenamePath to the file.
Returns the time the file was last changed, or FALSE on failure.
The time is returned as a Unix timestamp.
Example #1 A filectime() example
<?php
// outputs e.g. somefile.txt was last changed: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last changed: " . date("F d Y H:i:s.", filectime($filename));
}
?>
Upon failure, an E_WARNING is emitted.
Note:
Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().
Note:
Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.
Note:
Note that time resolution may differ from one file system to another.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
filegroup — Gets file group
$filename
) : intGets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.
filenamePath to the file.
Returns the group ID of the file, or FALSE if
an error occurs. The group ID is returned in numerical format, use
posix_getgrgid() to resolve it to a group name.
Upon failure, FALSE is returned.
Example #1 Finding the group of a file
<?php
$filename = 'index.php';
print_r(posix_getgrgid(filegroup($filename)));
?>
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
fileinode — Gets file inode
$filename
) : intGets the file inode.
filenamePath to the file.
Returns the inode number of the file, or FALSE on failure.
Example #1 Comparing the inode of a file with the current file
<?php
$filename = 'index.php';
if (getmyinode() == fileinode($filename)) {
echo 'You are checking the current file.';
}
?>
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
filemtime — Gets file modification time
$filename
) : intThis function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.
filenamePath to the file.
Returns the time the file was last modified, or FALSE on failure.
The time is returned as a Unix timestamp, which is
suitable for the date() function.
Example #1 filemtime() example
<?php
// outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>
Upon failure, an E_WARNING is emitted.
Note:
Note that time resolution may differ from one file system to another.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
fileowner — Gets file owner
$filename
) : intGets the file owner.
filenamePath to the file.
Returns the user ID of the owner of the file, or FALSE on failure.
The user ID is returned in numerical format, use
posix_getpwuid() to resolve it to a username.
Example #1 Finding the owner of a file
<?php
$filename = 'index.php';
print_r(posix_getpwuid(fileowner($filename)));
?>
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
fileperms — Gets file permissions
$filename
) : intGets permissions for the given file.
filenamePath to the file.
Returns the file's permissions as a numeric mode. Lower bits of this mode
are the same as the permissions expected by chmod(),
however on most platforms the return value will also include information on
the type of file given as filename. The examples
below demonstrate how to test the return value for specific permissions and
file types on POSIX systems, including Linux and macOS.
For local files, the specific return value is that of the
st_mode member of the structure returned by the C
library's stat() function. Exactly which bits are set
can vary from platform to platform, and looking up your specific platform's
documentation is recommended if parsing the non-permission bits of the
return value is required.
Example #1 Display permissions as an octal value
<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>
The above example will output:
1777 0644
Example #2 Display full permissions
<?php
$perms = fileperms('/etc/passwd');
switch ($perms & 0xF000) {
case 0xC000: // socket
$info = 's';
break;
case 0xA000: // symbolic link
$info = 'l';
break;
case 0x8000: // regular
$info = 'r';
break;
case 0x6000: // block special
$info = 'b';
break;
case 0x4000: // directory
$info = 'd';
break;
case 0x2000: // character special
$info = 'c';
break;
case 0x1000: // FIFO pipe
$info = 'p';
break;
default: // unknown
$info = 'u';
}
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x' ) :
(($perms & 0x0800) ? 'S' : '-'));
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x' ) :
(($perms & 0x0400) ? 'S' : '-'));
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x' ) :
(($perms & 0x0200) ? 'T' : '-'));
echo $info;
?>
The above example will output:
-rw-r--r--
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
filesize — Gets file size
$filename
) : intGets the size for the given file.
filenamePath to the file.
Returns the size of the file in bytes, or FALSE (and generates an error
of level E_WARNING) in case of an error.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Example #1 filesize() example
<?php
// outputs e.g. somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
?>
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
filetype — Gets file type
$filename
) : stringReturns the type of the given file.
filenamePath to the file.
Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket and unknown.
Returns FALSE if an error occurs. filetype() will also
produce an E_NOTICE message if the stat call fails
or if the file type is unknown.
Example #1 filetype() example
<?php
echo filetype('/etc/passwd'); // file
echo filetype('/etc/'); // dir
?>
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
flock — Portable advisory file locking
$handle
, int $operation
[, int &$wouldblock
] ) : boolflock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).
On versions of PHP before 5.3.2, the lock is released also by fclose() (which is also called automatically when script finished).
PHP supports a portable way of locking complete files in an advisory way
(which means all accessing programs have to use the same way of locking
or it will not work). By default, this function will block until the
requested lock is acquired; this may be controlled with the LOCK_NB option documented below.
handleA file system pointer resource that is typically created using fopen().
operation
operation is one of the following:
LOCK_SH to acquire a shared lock (reader).
LOCK_EX to acquire an exclusive lock (writer).
LOCK_UN to release a lock (shared or exclusive).
It is also possible to add LOCK_NB as a bitmask to one
of the above operations, if flock() should not
block during the locking attempt.
wouldblockThe optional third argument is set to 1 if the lock would block (EWOULDBLOCK errno condition).
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.5.22, 5.6.6 |
Added support for the wouldblock parameter on
Windows.
|
| 5.3.2 | The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually. |
Example #1 flock() example
<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>
Example #2 flock() using the LOCK_NB option
<?php
$fp = fopen('/tmp/lock.txt', 'r+');
/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fp, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain lock';
exit(-1);
}
/* ... */
fclose($fp);
?>
Note:
flock() uses mandatory locking instead of advisory locking on Windows. Mandatory locking is also supported on Linux and System V based operating systems via the usual mechanism supported by the fcntl() system call: that is, if the file in question has the setgid permission bit set and the group execution bit cleared. On Linux, the file system will also need to be mounted with the mand option for this to work.
Note:
Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()).
Note:
May only be used on file pointers returned by fopen() for local files, or file pointers pointing to userspace streams that implement the streamWrapper::stream_lock() method.
Assigning another value to handle argument in
subsequent code will release the lock.
On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!
flock() is not supported on antiquated filesystems like
FAT and its derivates and will therefore always
return FALSE under these environments.
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
fnmatch — Match filename against a pattern
$pattern
, string $string
[, int $flags = 0
] ) : bool
fnmatch() checks if the passed string would
match the given shell wildcard pattern.
patternThe shell wildcard pattern.
stringThe tested string. This function is especially useful for filenames, but may also be used on regular strings.
The average user may be used to shell patterns or at least in their
simplest form to '?' and '*'
wildcards so using fnmatch() instead of
preg_match() for
frontend search expression input may be way more convenient for
non-programming users.
flags
The value of flags can be any combination of
the following flags, joined with the
binary OR (|) operator.
Flag |
Description |
|---|---|
FNM_NOESCAPE |
Disable backslash escaping. |
FNM_PATHNAME |
Slash in string only matches slash in the given pattern. |
FNM_PERIOD |
Leading period in string must be exactly matched by period in the given pattern. |
FNM_CASEFOLD |
Caseless match. Part of the GNU extension. |
Returns TRUE if there is a match, FALSE otherwise.
| Version | Description |
|---|---|
| 5.3.0 | This function is now available on Windows platforms. |
Example #1 Checking a color name against a shell wildcard pattern
<?php
if (fnmatch("*gr[ae]y", $color)) {
echo "some form of gray ...";
}
?>
For now, this function is not available on non-POSIX compliant systems except Windows.
(PHP 4, PHP 5, PHP 7)
fopen — Opens file or URL
$filename
, string $mode
[, bool $use_include_path = FALSE
[, resource $context
]] ) : resource
fopen() binds a named resource, specified by
filename, to a stream.
filename
If filename is of the form "scheme://...", it
is assumed to be a URL and PHP will search for a protocol handler
(also known as a wrapper) for that scheme. If no wrappers for that
protocol are registered, PHP will emit a notice to help you track
potential problems in your script and then continue as though
filename specifies a regular file.
If PHP has decided that filename specifies
a local file, then it will try to open a stream on that file.
The file must be accessible to PHP, so you need to ensure that
the file access permissions allow this access.
If you have enabled safe mode
or open_basedir further
restrictions may apply.
If PHP has decided that filename specifies
a registered protocol, and that protocol is registered as a
network URL, PHP will check to make sure that
allow_url_fopen is
enabled. If it is switched off, PHP will emit a warning and
the fopen call will fail.
Note:
The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as
wrappers) supportcontextand/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini valueuser_agentused by thehttpwrapper).
On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.
<?php
$handle = fopen("c:\\folder\\resource.txt", "r");
?>
mode
The mode parameter specifies the type of access
you require to the stream. It may be any of the following:
mode |
Description |
|---|---|
'r' |
Open for reading only; place the file pointer at the beginning of the file. |
'r+' |
Open for reading and writing; place the file pointer at the beginning of the file. |
'w' |
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. |
'w+' |
Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. |
'a' |
Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended. |
'a+' |
Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended. |
'x' |
Create and open for writing only; place the file pointer at the
beginning of the file. If the file already exists, the
fopen() call will fail by returning FALSE and
generating an error of level E_WARNING. If
the file does not exist, attempt to create it. This is equivalent
to specifying O_EXCL|O_CREAT flags for the
underlying open(2) system call.
|
'x+' |
Create and open for reading and writing; otherwise it has the
same behavior as 'x'.
|
'c' |
Open the file for writing only. If the file does not exist, it is
created. If it exists, it is neither truncated (as opposed to
'w'), nor the call to this function fails (as is
the case with 'x'). The file pointer is
positioned on the beginning of the file. This may be useful if it's
desired to get an advisory lock (see flock())
before attempting to modify the file, as using
'w' could truncate the file before the lock
was obtained (if truncation is desired,
ftruncate() can be used after the lock is
requested).
|
'c+' |
Open the file for reading and writing; otherwise it has the same
behavior as 'c'.
|
'e' |
Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems. |
Note:
Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use
\nas the line ending character, Windows based systems use\r\nas the line ending characters and Macintosh based systems (Mac OS Classic) used\ras the line ending character.If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will "look funny".
Windows offers a text-mode translation flag (
't') which will transparently translate\nto\r\nwhen working with the file. In contrast, you can also use'b'to force binary mode, which will not translate your data. To use these flags, specify either'b'or't'as the last character of themodeparameter.The default translation mode is
'b'. You can use the't'mode if you are working with plain-text files and you use\nto delimit your line endings in your script, but expect your files to be readable with applications such as old versions of notepad. You should use the'b'in all other cases.If you specify the 't' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with
\r\ncharacters.
Note:
For portability, it is also strongly recommended that you re-write code that uses or relies upon the
't'mode so that it uses the correct line endings and'b'mode instead.
use_include_path
The optional third use_include_path parameter
can be set to '1' or TRUE if you want to search for the file in the
include_path, too.
contextNote: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Returns a file pointer resource on success,
or FALSE on failure
Upon failure, an E_WARNING is emitted.
| Version | Description |
|---|---|
| 7.0.16, 7.1.2 |
The 'e' option was added.
|
| 5.2.6 |
The 'c' and 'c+' options were
added
|
Example #1 fopen() examples
<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>
When using SSL, Microsoft IIS
will violate the protocol by closing the connection without sending a
close_notify indicator. PHP will report this as "SSL: Fatal
Protocol Error" when you reach the end of the data. To work around this, the
value of error_reporting should be
lowered to a level that does not include warnings.
PHP can detect buggy IIS server software when you open
the stream using the https:// wrapper and will suppress the
warning. When using fsockopen() to create an
ssl:// socket, the developer is responsible for detecting
and suppressing this warning.
Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
Note:
If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.
Note:
This function may also succeed when
filenameis a directory. If you are unsure whetherfilenameis a file or a directory, you may need to use the is_dir() function before calling fopen().
(PHP 4, PHP 5, PHP 7)
fpassthru — Output all remaining data on a file pointer
$handle
) : intReads to EOF on the given file pointer from the current position and writes the results to the output buffer.
You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.
If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readfile(), which saves you the fopen() call.
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
If an error occurs, fpassthru() returns
FALSE. Otherwise, fpassthru() returns
the number of characters read from handle
and passed through to the output.
Example #1 Using fpassthru() with binary files
<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
exit;
?>
Note:
When using fpassthru() on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a
bto the mode used in the call to fopen().You are encouraged to use the
bflag when dealing with binary files, even if your system does not require it, so that your scripts will be more portable.
(PHP 5 >= 5.1.0, PHP 7)
fputcsv — Format line as CSV and write to file pointer
$handle
, array $fields
[, string $delimiter = ","
[, string $enclosure = '"'
[, string $escape_char = "\\"
]]] ) : int
fputcsv() formats a line (passed as a
fields array) as CSV and writes it (terminated by a
newline) to the specified file handle.
handleThe file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
fieldsAn array of strings.
delimiter
The optional delimiter parameter sets the field
delimiter (one character only).
enclosure
The optional enclosure parameter sets the field
enclosure (one character only).
escape_char
The optional escape_char parameter sets the
escape character (at most one character).
An empty string ("") disables the proprietary escape mechanism.
Note:
If an
enclosurecharacter is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by anescape_char.
Returns the length of the written string or FALSE on failure.
| Version | Description |
|---|---|
| 7.4.0 |
The escape_char parameter now also accepts an empty
string to disable the proprietary escape mechanism.
|
| 5.5.4 |
The escape_char parameter was added
|
Example #1 fputcsv() example
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
The above example will write the following to file.csv:
aaa,bbb,ccc,dddd 123,456,789 """aaa""","""bbb"""
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
This function is an alias of: fwrite().
(PHP 4, PHP 5, PHP 7)
fread — Binary-safe file read
$handle
, int $length
) : string
fread() reads up to
length bytes from the file pointer
referenced by handle. Reading stops as soon as one
of the following conditions is met:
length bytes have been read
Returns the read string or FALSE on failure.
Example #1 A simple fread() example
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Example #2 Binary fread() example
On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.
<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Example #3 Remote fread() examples
When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below.
<?php
// For PHP 5 and up
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("http://www.example.com/", "rb");
if (FALSE === $handle) {
exit("Failed to open stream to URL");
}
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>
Note:
If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.
Note:
Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
fscanf — Parses input from a file according to a format
The function fscanf() is similar to
sscanf(), but it takes its input from a file
associated with handle and interprets the
input according to the specified format, which is
described in the documentation for sprintf().
Any whitespace in the format string matches any whitespace in the input
stream. This means that even a tab \t in the format
string can match a single space character in the input stream.
Each call to fscanf() reads one line from the file.
handleA file system pointer resource that is typically created using fopen().
format
The format string is composed of zero or more directives:
ordinary characters (excluding %) that are
copied directly to the result and conversion
specifications, each of which results in fetching its
own parameter.
A conversion specification follows this prototype:
%[argnum$][flags][width][.precision]specifier.
An integer followed by a dollar sign $,
to specify which number argument to treat in the conversion.
| Flag | Description |
|---|---|
- |
Left-justify within the given field width; Right justification is the default |
+ |
Prefix positive numbers with a plus sign
+; Default only negative
are prefixed with a negative sign.
|
(space) |
Pads the result with spaces. This is the default. |
0 |
Only left-pads numbers with zeros.
With s specifiers this can
also right-pad with zeros.
|
'(char) |
Pads the result with the character (char). |
An integer that says how many characters (minimum) this conversion should result in.
A period . followed by an integer
who's meaning depends on the specifier:
e, E,
f and F
specifiers: this is the number of digits to be printed
after the decimal point (by default, this is 6).
g and G
specifiers: this is the maximum number of significant
digits to be printed.
s specifier: it acts as a cutoff point,
setting a maximum character limit to the string.
Note: If the period is specified without an explicit value for precision, 0 is assumed.
Note: Attempting to use a position specifier greater than
PHP_INT_MAXwill generate warnings.
| Specifier | Description |
|---|---|
% |
A literal percent character. No argument is required. |
b |
The argument is treated as an integer and presented as a binary number. |
c |
The argument is treated as an integer and presented as the character with that ASCII. |
d |
The argument is treated as an integer and presented as a (signed) decimal number. |
e |
The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less). |
E |
Like the e specifier but uses
uppercase letter (e.g. 1.2E+2).
|
f |
The argument is treated as a float and presented as a floating-point number (locale aware). |
F |
The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3. |
g |
General format. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X: If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1. |
G |
Like the g specifier but uses
E and f.
|
o |
The argument is treated as an integer and presented as an octal number. |
s |
The argument is treated and presented as a string. |
u |
The argument is treated as an integer and presented as an unsigned decimal number. |
x |
The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
X |
The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
The c type specifier ignores padding and width
Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results
Variables will be co-erced to a suitable type for the specifier:
| Type | Specifiers |
|---|---|
string |
s |
integer |
d,
u,
c,
o,
x,
X,
b
|
double |
g,
G,
e,
E,
f,
F
|
...The optional assigned values.
If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.
Example #1 fscanf() Example
<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
list ($name, $profession, $countrycode) = $userinfo;
//... do something with the values
}
fclose($handle);
?>
Example #2 Contents of users.txt
javier argonaut pe hiroshi sculptor jp robert slacker us luigi florist it
(PHP 4, PHP 5, PHP 7)
fseek — Seeks on a file pointer
$handle
, int $offset
[, int $whence = SEEK_SET
] ) : int
Sets the file position indicator for the file referenced by
handle. The new position, measured in bytes
from the beginning of the file, is obtained by adding
offset to the position specified by
whence.
In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage.
handleA file system pointer resource that is typically created using fopen().
offsetThe offset.
To move to a position before the end-of-file, you need to pass
a negative value in offset and
set whence
to SEEK_END.
whence
whence values are:
SEEK_SET - Set position equal to offset bytes.SEEK_CUR - Set position to current location plus offset.SEEK_END - Set position to end-of-file plus offset.Upon success, returns 0; otherwise, returns -1.
Example #1 fseek() example
<?php
$fp = fopen('somefile.txt', 'r');
// read some data
$data = fgets($fp, 4096);
// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);
?>
Note:
If you have opened the file in append (
aora+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.
Note:
Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail.
(PHP 4, PHP 5, PHP 7)
fstat — Gets information about a file using an open file pointer
$handle
) : array
Gathers the statistics of the file opened by the file
pointer handle. This function is similar to the
stat() function except that it operates
on an open file pointer instead of a filename.
Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.
Example #1 fstat() example
<?php
// open a file
$fp = fopen("/etc/passwd", "r");
// gather statistics
$fstat = fstat($fp);
// close the file
fclose($fp);
// print only the associative part
print_r(array_slice($fstat, 13));
?>
The above example will output something similar to:
Array
(
[dev] => 771
[ino] => 488704
[mode] => 33188
[nlink] => 1
[uid] => 0
[gid] => 0
[rdev] => 0
[size] => 1114
[atime] => 1061067181
[mtime] => 1056136526
[ctime] => 1056136526
[blksize] => 4096
[blocks] => 8
)
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
(PHP 4, PHP 5, PHP 7)
ftell — Returns the current position of the file read/write pointer
$handle
) : int
Returns the position of the file pointer referenced by handle.
Returns the position of the file pointer referenced by
handle as an integer; i.e., its offset into the file stream.
If an error occurs, returns FALSE.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Example #1 ftell() example
<?php
// opens a file and read some data
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);
// where are we ?
echo ftell($fp); // 11
fclose($fp);
?>
(PHP 4, PHP 5, PHP 7)
ftruncate — Truncates a file to a given length
$handle
, int $size
) : bool
Takes the filepointer, handle, and truncates the file to
length, size.
handleThe file pointer.
Note:
The
handlemust be open for writing.
sizeThe size to truncate to.
Note:
If
sizeis larger than the file then the file is extended with null bytes.If
sizeis smaller than the file then the file is truncated to that size.
Returns TRUE on success or FALSE on failure.
Example #1 File truncation example
<?php
$filename = 'lorem_ipsum.txt';
$handle = fopen($filename, 'r+');
ftruncate($handle, rand(1, filesize($filename)));
rewind($handle);
echo fread($handle, filesize($filename));
fclose($handle);
?>
Note:
The file pointer is not changed.
(PHP 4, PHP 5, PHP 7)
fwrite — Binary-safe file write
$handle
, string $string
[, int $length
] ) : int
fwrite() writes the contents of
string to the file stream pointed to by
handle.
handleA file system pointer resource that is typically created using fopen().
stringThe string that is to be written.
length
If the length argument is given, writing will
stop after length bytes have been written or
the end of string is reached, whichever comes
first.
Note that if the length argument is given,
then the magic_quotes_runtime
configuration option will be ignored and no slashes will be
stripped from string.
fwrite() returns the number of bytes
written, or FALSE on error.
Note:
Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:
<?php
function fwrite_stream($fp, $string) {
for ($written = 0; $written < strlen($string); $written += $fwrite) {
$fwrite = fwrite($fp, substr($string, $written));
if ($fwrite === false) {
return $written;
}
}
return $written;
}
?>
Note:
On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.
Note:
If
handlewas fopen()ed in append mode, fwrite()s are atomic (unless the size ofstringexceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.
Note:
If writing twice to the file pointer, then the data will be appended to the end of the file content:
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
Example #1 A simple fwrite() example
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
glob — Find pathnames matching a pattern
$pattern
[, int $flags = 0
] ) : array
The glob() function searches for all the pathnames
matching pattern according to the rules used by
the libc glob() function, which is similar to the rules used by common
shells.
patternThe pattern. No tilde expansion or parameter substitution is done.
Special characters:
* - Matches zero or more characters.
? - Matches exactly one character (any character).
[...] - Matches one character from a group of
characters. If the first character is !,
matches any character not in the group.
\ - Escapes the following character,
except when the GLOB_NOESCAPE flag is used.
flagsValid flags:
GLOB_MARK - Adds a slash (a backslash on Windows) to each directory returned
GLOB_NOSORT - Return files as they appear in the
directory (no sorting). When this flag is not used, the pathnames are
sorted alphabetically
GLOB_NOCHECK - Return the search pattern if no
files matching it were found
GLOB_NOESCAPE - Backslashes do not quote
metacharacters
GLOB_BRACE - Expands {a,b,c} to match 'a', 'b',
or 'c'
GLOB_ONLYDIR - Return only directory entries
which match the pattern
GLOB_ERR - Stop on read errors (like unreadable
directories), by default errors are ignored.
Returns an array containing the matched files/directories, an empty array
if no file matched or FALSE on error.
Note:
On some systems it is impossible to distinguish between empty match and an error.
| Version | Description |
|---|---|
| 5.1.0 |
GLOB_ERR was added
|
Example #1 Convenient way how glob() can replace opendir() and friends.
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
The above example will output something similar to:
funclist.txt size 44686 funcsummary.txt size 267625 quickref.txt size 137820
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
Note: This function isn't available on some systems (e.g. old Sun OS).
Note: The
GLOB_BRACEflag is not available on some non GNU systems, like Solaris.
(PHP 4, PHP 5, PHP 7)
is_dir — Tells whether the filename is a directory
$filename
) : boolTells whether the given filename is a directory.
filename
Path to the file. If filename is a relative
filename, it will be checked relative to the current working
directory. If filename is a symbolic or hard link
then the link will be resolved and checked. If you have enabled safe mode,
or open_basedir further
restrictions may apply.
Returns TRUE if the filename exists and is a directory, FALSE
otherwise.
Example #1 is_dir() example
<?php
var_dump(is_dir('a_file.txt'));
var_dump(is_dir('bogus_dir/abc'));
var_dump(is_dir('..')); //one dir up
?>
The above example will output:
bool(false) bool(false) bool(true)
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
is_executable — Tells whether the filename is executable
$filename
) : boolTells whether the filename is executable.
filenamePath to the file.
Returns TRUE if the filename exists and is executable, or FALSE on
error.
Example #1 is_executable() example
<?php
$file = '/home/vincent/somefile.sh';
if (is_executable($file)) {
echo $file.' is executable';
} else {
echo $file.' is not executable';
}
?>
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
is_file — Tells whether the filename is a regular file
$filename
) : boolTells whether the given file is a regular file.
filenamePath to the file.
Returns TRUE if the filename exists and is a regular file, FALSE
otherwise.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Example #1 is_file() example
<?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>
The above example will output:
bool(true) bool(false)
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
is_link — Tells whether the filename is a symbolic link
$filename
) : boolTells whether the given file is a symbolic link.
filenamePath to the file.
Returns TRUE if the filename exists and is a symbolic link, FALSE
otherwise.
Example #1 Create and confirm if a file is a symbolic link
<?php
$link = 'uploads';
if (is_link($link)) {
echo(readlink($link));
} else {
symlink('uploads.php', $link);
}
?>
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
is_readable — Tells whether a file exists and is readable
$filename
) : boolTells whether a file exists and is readable.
filenamePath to the file.
Returns TRUE if the file or directory specified by
filename exists and is readable, FALSE otherwise.
Example #1 is_readable() example
<?php
$filename = 'test.txt';
if (is_readable($filename)) {
echo 'The file is readable';
} else {
echo 'The file is not readable';
}
?>
Upon failure, an E_WARNING is emitted.
Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account before PHP 5.1.5.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
Note:
The check is done using the real UID/GID instead of the effective one.
This function may return TRUE for directories. Use
is_dir() to distinguish file and directory.
(PHP 4 >= 4.0.3, PHP 5, PHP 7)
is_uploaded_file — Tells whether the file was uploaded via HTTP POST
$filename
) : bool
Returns TRUE if the file named by filename was
uploaded via HTTP POST. This is useful to help ensure that a
malicious user hasn't tried to trick the script into working on
files upon which it should not be working--for instance,
/etc/passwd.
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the client's machine $_FILES['userfile']['name'] does not work.
filenameThe filename being checked.
Returns TRUE on success or FALSE on failure.
Example #1 is_uploaded_file() example
<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
echo "Displaying contents\n";
readfile($_FILES['userfile']['tmp_name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
}
?>
(PHP 4, PHP 5, PHP 7)
is_writable — Tells whether the filename is writable
$filename
) : bool
Returns TRUE if the filename exists and is
writable. The filename argument may be a directory name allowing you
to check if a directory is writable.
Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.
filenameThe filename being checked.
Returns TRUE if the filename exists and is
writable.
Example #1 is_writable() example
<?php
$filename = 'test.txt';
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
?>
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
This function is an alias of: is_writable().
(PHP 5 >= 5.1.3, PHP 7)
lchgrp — Changes group ownership of symlink
Attempts to change the group of the symlink filename
to group.
Only the superuser may change the group of a symlink arbitrarily; other users may change the group of a symlink to any group of which that user is a member.
filenamePath to the symlink.
groupThe group specified by name or number.
Returns TRUE on success or FALSE on failure.
Example #1 Changing the group of a symbolic link
<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);
lchgrp($link, 8);
?>
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
Note: This function is not implemented on Windows platforms.
(PHP 5 >= 5.1.3, PHP 7)
lchown — Changes user ownership of symlink
Attempts to change the owner of the symlink filename
to user user.
Only the superuser may change the owner of a symlink.
filenamePath to the file.
userUser name or number.
Returns TRUE on success or FALSE on failure.
Example #1 Changing the owner of a symbolic link
<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);
lchown($link, 8);
?>
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
Note: This function is not implemented on Windows platforms.
(PHP 4, PHP 5, PHP 7)
link — Create a hard link
$target
, string $link
) : boollink() creates a hard link.
targetTarget of the link.
linkThe link name.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater). |
Example #1 Creating a simple hard link
<?php
$target = 'source.ext'; // This is the file that already exists
$link = 'newfile.ext'; // This the filename that you want to link it to
link($target, $link);
?>
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
Note: For Windows only: This function requires PHP to run in an elevated mode or with the UAC disabled.
(PHP 4, PHP 5, PHP 7)
linkinfo — Gets information about a link
$path
) : intGets information about a link.
This function is used to verify if a link (pointed to by
path) really exists (using the same method as the
S_ISLNK macro defined in stat.h).
pathPath to the link.
linkinfo() returns the st_dev field
of the Unix C stat structure returned by the lstat
system call. Returns a non-negative integer on success, -1 in case the link was not found,
or FALSE if an open.base_dir violation occurs.
| Version | Description |
|---|---|
| 5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater). |
Example #1 linkinfo() example
<?php
echo linkinfo('/vmlinuz'); // 835
?>
(PHP 4, PHP 5, PHP 7)
lstat — Gives information about a file or symbolic link
$filename
) : array
Gathers the statistics of the file or symbolic link named by
filename.
filenamePath to a file or a symbolic link.
See the manual page for stat() for information on
the structure of the array that lstat() returns.
This function is identical to the stat() function
except that if the filename parameter is a symbolic
link, the status of the symbolic link is returned, not the status of the
file pointed to by the symbolic link.
Example #1 Comparison of stat() and lstat()
<?php
symlink('uploads.php', 'uploads');
// Contrast information for uploads.php and uploads
array_diff(stat('uploads'), lstat('uploads'));
?>
The above example will output something similar to:
Information that differs between the two files.
Array
(
[ino] => 97236376
[mode] => 33188
[size] => 34
[atime] => 1223580003
[mtime] => 1223581848
[ctime] => 1223581848
[blocks] => 8
)
Upon failure, an E_WARNING is emitted.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
mkdir — Makes directory
$pathname
[, int $mode = 0777
[, bool $recursive = FALSE
[, resource $context
]]] ) : boolAttempts to create the directory specified by pathname.
pathnameThe directory path.
modeThe mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page.
Note:
modeis ignored on Windows.
Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask().
recursive
Allows the creation of nested directories specified in the
pathname.
contextNote: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Returns TRUE on success or FALSE on failure.
Example #1 mkdir() example
<?php
mkdir("/path/to/my/dir", 0700);
?>
Example #2 mkdir() using the recursive parameter
<?php
// Desired folder structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0777, true)) {
die('Failed to create folders...');
}
// ...
?>
Emits an E_WARNING level error if the directory
already exists.
Emits an E_WARNING level error if the relevant
permissions prevent creating the directory.
Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
(PHP 4 >= 4.0.3, PHP 5, PHP 7)
move_uploaded_file — Moves an uploaded file to a new location
$filename
, string $destination
) : bool
This function checks to ensure that the file designated by
filename is a valid upload file (meaning
that it was uploaded via PHP's HTTP POST upload mechanism). If
the file is valid, it will be moved to the filename given by
destination.
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
filenameThe filename of the uploaded file.
destinationThe destination of the moved file.
Returns TRUE on success.
If filename is not a valid upload file,
then no action will occur, and
move_uploaded_file() will return
FALSE.
If filename is a valid upload file, but
cannot be moved for some reason, no action will occur, and
move_uploaded_file() will return
FALSE. Additionally, a warning will be issued.
Example #1 Uploading multiple files
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
Note:
move_uploaded_file() is both safe mode and open_basedir aware. However, restrictions are placed only on the
destinationpath as to allow the moving of uploaded files in whichfilenamemay conflict with such restrictions. move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved.
If the destination file already exists, it will be overwritten.
(PHP 4, PHP 5, PHP 7)
parse_ini_file — Parse a configuration file
$filename
[, bool $process_sections = FALSE
[, int $scanner_mode = INI_SCANNER_NORMAL
]] ) : array
parse_ini_file() loads in the
ini file specified in filename,
and returns the settings in it in an associative array.
The structure of the ini file is the same as the php.ini's.
filenameThe filename of the ini file being parsed.
process_sections
By setting the process_sections
parameter to TRUE, you get a multidimensional array, with
the section names and settings included. The default
for process_sections is FALSE
scanner_mode
Can either be INI_SCANNER_NORMAL (default) or
INI_SCANNER_RAW. If INI_SCANNER_RAW
is supplied, then option values will not be parsed.
As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED.
In this mode boolean, null and integer types are preserved when possible.
String values "true", "on" and "yes"
are converted to TRUE. "false", "off", "no"
and "none" are considered FALSE. "null" is converted to NULL
in typed mode. Also, all numeric strings are converted to integer type if it is possible.
The settings are returned as an associative array on success,
and FALSE on failure.
| Version | Description |
|---|---|
| 7.0.0 |
Hash marks (#) are no longer recognized as comments.
|
| 5.6.1 |
Added new INI_SCANNER_TYPED mode.
|
| 5.3.0 |
Added optional scanner_mode parameter.
Single quotes may now be used around variable assignments.
Hash marks (#) should no longer be used as comments
and will throw a deprecation warning if used.
|
| 5.2.7 |
On syntax error this function will return FALSE rather than an empty
array.
|
| 5.2.4 | Keys and section names consisting of numbers are now evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals. |
Example #1 Contents of sample.ini
; This is a sample configuration file ; Comments start with ';', as in php.ini [first_section] one = 1 five = 5 animal = BIRD [second_section] path = "/usr/local/bin" URL = "http://www.example.com/~username" [third_section] phpversion[] = "5.0" phpversion[] = "5.1" phpversion[] = "5.2" phpversion[] = "5.3" urls[svn] = "http://svn.php.net" urls[git] = "http://git.php.net"
Example #2 parse_ini_file() example
Constants may also be parsed in the ini file so if you define a constant as an ini value before running parse_ini_file(), it will be integrated into the results. Only ini values are evaluated. For example:
<?php
define('BIRD', 'Dodo bird');
// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);
// Parse with sections
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);
?>
The above example will output something similar to:
Array
(
[one] => 1
[five] => 5
[animal] => Dodo bird
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
[phpversion] => Array
(
[0] => 5.0
[1] => 5.1
[2] => 5.2
[3] => 5.3
)
[urls] => Array
(
[svn] => http://svn.php.net
[git] => http://git.php.net
)
)
Array
(
[first_section] => Array
(
[one] => 1
[five] => 5
[animal] => Dodo bird
)
[second_section] => Array
(
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
)
[third_section] => Array
(
[phpversion] => Array
(
[0] => 5.0
[1] => 5.1
[2] => 5.2
[3] => 5.3
)
[urls] => Array
(
[svn] => http://svn.php.net
[git] => http://git.php.net
)
)
)
Example #3 parse_ini_file() parsing a php.ini file
<?php
// A simple function used for comparing the results below
function yesno($expression)
{
return($expression ? 'Yes' : 'No');
}
// Get the path to php.ini using the php_ini_loaded_file()
// function available as of PHP 5.2.4
$ini_path = php_ini_loaded_file();
// Parse php.ini
$ini = parse_ini_file($ini_path);
// Print and compare the values, note that using get_cfg_var()
// will give the same results for parsed and loaded here
echo '(parsed) magic_quotes_gpc = ' . yesno($ini['magic_quotes_gpc']) . PHP_EOL;
echo '(loaded) magic_quotes_gpc = ' . yesno(get_cfg_var('magic_quotes_gpc')) . PHP_EOL;
?>
The above example will output something similar to:
(parsed) magic_quotes_gpc = Yes (loaded) magic_quotes_gpc = Yes
Note:
This function has nothing to do with the php.ini file. It is already processed by the time you run your script. This function can be used to read in your own application's configuration files.
Note:
If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes (").
Note: There are reserved words which must not be used as keys for ini files. These include:
null,yes,no,true,false,on,off,none. Valuesnull,off,noandfalseresult in"", and valueson,yesandtrueresult in"1", unlessINI_SCANNER_TYPEDmode is used (as of PHP 5.6.1). Characters?{}|&~!()^"must not be used anywhere in the key and have a special meaning in the value.
Note:
Entries without an equal sign are ignored. For example, "foo" is ignored whereas "bar =" is parsed and added with an empty value. For example, MySQL has a "no-auto-rehash" setting in my.cnf that does not take a value, so it is ignored.
(PHP 5 >= 5.3.0, PHP 7)
parse_ini_string — Parse a configuration string
$ini
[, bool $process_sections = FALSE
[, int $scanner_mode = INI_SCANNER_NORMAL
]] ) : array
parse_ini_string() returns the settings in string
ini in an associative array.
The structure of the ini string is the same as the php.ini's.
iniThe contents of the ini file being parsed.
process_sections
By setting the process_sections
parameter to TRUE, you get a multidimensional array, with
the section names and settings included. The default
for process_sections is FALSE
scanner_mode
Can either be INI_SCANNER_NORMAL (default) or
INI_SCANNER_RAW. If INI_SCANNER_RAW
is supplied, then option values will not be parsed.
As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED.
In this mode boolean, null and integer types are preserved when possible.
String values "true", "on" and "yes"
are converted to TRUE. "false", "off", "no"
and "none" are considered FALSE. "null" is converted to NULL
in typed mode. Also, all numeric strings are converted to integer type if it is possible.
The settings are returned as an associative array on success,
and FALSE on failure.
Note: There are reserved words which must not be used as keys for ini files. These include:
null,yes,no,true,false,on,off,none. Valuesnull,off,noandfalseresult in"", and valueson,yesandtrueresult in"1", unlessINI_SCANNER_TYPEDmode is used. Characters?{}|&~![()^"must not be used anywhere in the key and have a special meaning in the value.
(PHP 4 >= 4.0.3, PHP 5, PHP 7)
pathinfo — Returns information about a file path
$path
[, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME
] ) : mixed
pathinfo() returns information about
path: either an associative array or a string,
depending on options.
Note:
For information on retrieving the current path info, read the section on predefined reserved variables.
pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.
pathThe path to be parsed.
options
If present, specifies a specific element to be returned; one of
PATHINFO_DIRNAME,
PATHINFO_BASENAME,
PATHINFO_EXTENSION or
PATHINFO_FILENAME.
If options is not specified, returns all
available elements.
If the options parameter is not passed, an
associative array containing the following elements is
returned:
dirname, basename,
extension (if any), and filename.
Note:
If the
pathhas more than one extension,PATHINFO_EXTENSIONreturns only the last one andPATHINFO_FILENAMEonly strips the last one. (see first example below).
Note:
If the
pathdoes not have an extension, noextensionelement will be returned (see second example below).
Note:
If the
basenameof thepathstarts with a dot, the following characters are interpreted asextension, and thefilenameis empty (see third example below).
If options is present, returns a
string containing the requested element.
| Version | Description |
|---|---|
| 5.2.0 |
The PATHINFO_FILENAME constant was added.
|
Example #1 pathinfo() Example
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>
The above example will output:
/www/htdocs/inc lib.inc.php php lib.inc
Example #2 pathinfo() example showing difference between null and no extension
<?php
$path_parts = pathinfo('/path/emptyextension.');
var_dump($path_parts['extension']);
$path_parts = pathinfo('/path/noextension');
var_dump($path_parts['extension']);
?>
The above example will output something similar to:
string(0) "" Notice: Undefined index: extension in test.php on line 6 NULL
Example #3 pathinfo() example for a dot-file
<?php
print_r(pathinfo('/some/path/.test'));
?>
The above example will output something similar to:
Array
(
[dirname] => /some/path
[basename] => .test
[extension] => test
[filename] =>
)
(PHP 4, PHP 5, PHP 7)
pclose — Closes process file pointer
handleThe file pointer must be valid, and must have been returned by a successful call to popen().
Returns the termination status of the process that was run. In case of
an error then -1 is returned.
Note:
If PHP has been compiled with --enable-sigchild, the return value of this function is undefined.
Example #1 pclose() example
<?php
$handle = popen('/bin/ls', 'r');
pclose($handle);
?>
Note: Unix Only:
pclose() is internally implemented using the
waitpid(3)system call. To obtain the real exit status code the pcntl_wexitstatus() function should be used.
(PHP 4, PHP 5, PHP 7)
popen — Opens process file pointer
$command
, string $mode
) : resource
Opens a pipe to a process executed by forking the command given
by command.
commandThe command
modeThe mode
Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite(). When the mode is 'r', the returned file pointer equals to the STDOUT of the command, when the mode is 'w', the returned file pointer equals to the STDIN of the command.
If an error occurs, returns FALSE.
Example #1 popen() example
<?php
$handle = popen("/bin/ls", "r");
?>
If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:
Example #2 popen() example
<?php
error_reporting(E_ALL);
/* Add redirection so we can get stderr. */
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>
Note:
If you're looking for bi-directional support (two-way), use proc_open().
Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have
..components in the path to the executable.
With safe mode enabled,
the command string is escaped with escapeshellcmd(). Thus,
echo y | echo x becomes echo y \| echo x.
(PHP 4, PHP 5, PHP 7)
readfile — Outputs a file
$filename
[, bool $use_include_path = FALSE
[, resource $context
]] ) : intReads a file and writes it to the output buffer.
filenameThe filename being read.
use_include_path
You can use the optional second parameter and set it to TRUE, if
you want to search for the file in the include_path, too.
contextA context stream resource.
Returns the number of bytes read from the file on success,
or FALSE on failure
Upon failure, an E_WARNING is emitted.
Example #1 Forcing a download using readfile()
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
The above example will output something similar to:
Note:
readfile() will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with ob_get_level().
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
Note: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
(PHP 4, PHP 5, PHP 7)
readlink — Returns the target of a symbolic link
$path
) : stringreadlink() does the same as the readlink C function.
pathThe symbolic link path.
Returns the contents of the symbolic link path or FALSE on error.
Note: The function fails if
pathis not a symlink, except on Windows, where the normalized path will be returned.
| Version | Description |
|---|---|
| 5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater). |
Example #1 readlink() example
<?php
// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');
?>
(PHP 5 >= 5.3.2, PHP 7)
realpath_cache_get — Get realpath cache entries
Get the contents of the realpath cache.
Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache.
Example #1 realpath_cache_get() example
<?php
var_dump(realpath_cache_get());
?>
The above example will output something similar to:
array(2) {
["/test"]=>
array(4) {
["key"]=>
int(123456789)
["is_dir"]=>
bool(true)
["realpath"]=>
string(5) "/test"
["expires"]=>
int(1260318939)
}
["/test/test.php"]=>
array(4) {
["key"]=>
int(987654321)
["is_dir"]=>
bool(false)
["realpath"]=>
string(12) "/root/test.php"
["expires"]=>
int(1260318939)
}
}
(PHP 5 >= 5.3.2, PHP 7)
realpath_cache_size — Get realpath cache size
Get the amount of memory used by the realpath cache.
Returns how much memory realpath cache is using.
Example #1 realpath_cache_size() example
<?php
var_dump(realpath_cache_size());
?>
The above example will output something similar to:
int(412)
(PHP 4, PHP 5, PHP 7)
realpath — Returns canonicalized absolute pathname
$path
) : string
realpath() expands all symbolic links and
resolves references to /./, /../ and extra / characters in
the input path and returns the canonicalized
absolute pathname.
pathThe path being checked.
Note:
Whilst a path must be supplied, the value can be an empty string. In this case, the value is interpreted as the current directory.
Returns the canonicalized absolute pathname on success. The resulting path
will have no symbolic link, /./ or /../ components. Trailing delimiters,
such as \ and /, are also removed.
realpath() returns FALSE on failure, e.g. if
the file does not exist.
Note:
The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return
FALSE.
Note:
For case-insensitive filesystems realpath() may or may not normalize the character case.
Note:
The function realpath() will not work for a file which is inside a Phar as such path would be a virtual path, not a real one.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
| Version | Description |
|---|---|
| 5.3.0 |
Prior to this release, if only the last path
component did not exist, realpath() would not fail on
*BSD systems. realpath() now fails in this case.
|
| 5.2.1 |
Prior to this version, realpath() returned FALSE
if path is an empty string or NULL.
|
Example #1 realpath() example
<?php
chdir('/var/www/');
echo realpath('./../../etc/passwd') . PHP_EOL;
echo realpath('/tmp/') . PHP_EOL;
?>
The above example will output:
/etc/passwd /tmp
Example #2 realpath() on Windows
On windows realpath() will change unix style paths to windows style.
<?php
echo realpath('/windows/system32'), PHP_EOL;
echo realpath('C:\Program Files\\'), PHP_EOL;
?>
The above example will output:
C:\WINDOWS\System32 C:\Program Files
(PHP 4, PHP 5, PHP 7)
rename — Renames a file or directory
$oldname
, string $newname
[, resource $context
] ) : bool
Attempts to rename oldname to
newname, moving it between directories if necessary.
If renaming a file and newname exists,
it will be overwritten. If renaming a directory and
newname exists,
this function will emit a warning.
oldnameThe old name.
Note:
The wrapper used in
oldnamemust match the wrapper used innewname.
newnameThe new name.
contextNote: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.1 | rename() can now rename files across drives in Windows. |
Example #1 Example with rename()
<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>
(PHP 4, PHP 5, PHP 7)
rewind — Rewind the position of a file pointer
$handle
) : bool
Sets the file position indicator for handle
to the beginning of the file stream.
Note:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file pointer position.
handleThe file pointer must be valid, and must point to a file successfully opened by fopen().
Returns TRUE on success or FALSE on failure.
Example #1 rewind() overwriting example
<?php
$handle = fopen('output.txt', 'r+');
fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);
echo fread($handle, filesize('output.txt'));
fclose($handle);
?>
The above example will output something similar to:
Foolly long sentence.
(PHP 4, PHP 5, PHP 7)
rmdir — Removes directory
$dirname
[, resource $context
] ) : bool
Attempts to remove the directory named by dirname.
The directory must be empty, and the relevant permissions must permit this.
A E_WARNING level error will be generated on failure.
dirnamePath to the directory.
contextNote: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Returns TRUE on success or FALSE on failure.
Example #1 rmdir() example
<?php
if (!is_dir('examples')) {
mkdir('examples');
}
rmdir('examples');
?>
Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
This function is an alias of: stream_set_write_buffer().
(PHP 4, PHP 5, PHP 7)
stat — Gives information about a file
$filename
) : array
Gathers the statistics of the file named by
filename. If filename is a
symbolic link, statistics are from the file itself, not the symlink.
Prior to PHP 7.4.0, on Windows NTS builds the size,
atime, mtime and ctime
statistics have been from the symlink, in this case.
lstat() is identical to stat() except it would instead be based off the symlinks status.
filenamePath to the file.
| Numeric | Associative | Description |
|---|---|---|
| 0 | dev | device number *** |
| 1 | ino | inode number **** |
| 2 | mode | inode protection mode |
| 3 | nlink | number of links |
| 4 | uid | userid of owner * |
| 5 | gid | groupid of owner * |
| 6 | rdev | device type, if inode device |
| 7 | size | size in bytes |
| 8 | atime | time of last access (Unix timestamp) |
| 9 | mtime | time of last modification (Unix timestamp) |
| 10 | ctime | time of last inode change (Unix timestamp) |
| 11 | blksize | blocksize of filesystem IO ** |
| 12 | blocks | number of 512-byte blocks allocated ** |
* On Windows this will always be 0.
** Only valid on systems supporting the st_blksize type - other
systems (e.g. Windows) return -1.
*** On Windows, as of PHP 7.4.0, this is the serial number of the volume that contains the file,
which is a 64-bit unsigned integer, so may overflow.
Previously, it was the numeric representation of the drive letter (e.g. 2
for C:) for stat(), and 0 for
lstat().
**** On Windows, as of PHP 7.4.0, this is the identifier associated with the file,
which is a 64-bit unsigned integer, so may overflow.
Previously, it was always 0.
The value of mode contains information read by several functions.
When written in octal, starting from the right, the first three digits are returned by
chmod(). The next digit is ignored by PHP. The next two digits indicate
the file type:
mode in octal |
Meaning |
|---|---|
0120000 |
link |
0100000 |
regular file |
0060000 |
block device |
0040000 |
directory |
0010000 |
fifo |
0100644 and a directory could be
0040755.
In case of error, stat() returns FALSE.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Upon failure, an E_WARNING is emitted.
| Version | Description |
|---|---|
| 7.4.0 | On Windows, the device number is now the serial number of the volume that contains the file, and the inode number is the identifier associated with the file. |
| 7.4.0 |
The size, atime, mtime and
ctime statistics of symlinks are always those of the target.
This was previously not the case for NTS builds on Windows.
|
Example #1 stat() example
<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');
/*
* Print file access time, this is the same
* as calling fileatime()
*/
echo 'Access time: ' . $stat['atime'];
/*
* Print file modification time, this is the
* same as calling filemtime()
*/
echo 'Modification time: ' . $stat['mtime'];
/* Print the device number */
echo 'Device number: ' . $stat['dev'];
?>
Example #2 Using stat() information together with touch()
<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');
/* Did we failed to get stat information? */
if (!$stat) {
echo 'stat() call failed...';
} else {
/*
* We want the access time to be 1 week
* after the current access time.
*/
$atime = $stat['atime'] + 604800;
/* Touch the file */
if (!touch('some_file.txt', time(), $atime)) {
echo 'Failed to touch file...';
} else {
echo 'touch() returned success...';
}
}
?>
Note:
Note that time resolution may differ from one file system to another.
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
(PHP 4, PHP 5, PHP 7)
symlink — Creates a symbolic link
$target
, string $link
) : bool
symlink() creates a symbolic link to the existing
target with the specified name
link.
targetTarget of the link.
linkThe link name.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater). |
Example #1 Create a symbolic link
<?php
$target = 'uploads.php';
$link = 'uploads';
symlink($target, $link);
echo readlink($link);
?>
Note: Windows users should note that this function will only work if the system you run PHP from is Windows Vista/Windows Server 2008 or newer. Windows versions prior to that do not support symbolic links.
(PHP 4, PHP 5, PHP 7)
tempnam — Create file with unique file name
$dir
, string $prefix
) : stringCreates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist or is not writable, tempnam() may generate a file in the system's temporary directory, and return the full path to that file, including its name.
dirThe directory where the temporary filename will be created.
prefixThe prefix of the generated temporary filename.
Note: Only the first 63 characters of the prefix are used. Windows even uses only the first three characters of the prefix.
Returns the new temporary filename (with path), or FALSE on
failure.
Example #1 tempnam() example
<?php
$tmpfname = tempnam("/tmp", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);
// do here something
unlink($tmpfname);
?>
Note: If PHP cannot create a file in the specified
dirparameter, it falls back on the system default. On NTFS this also happens if the specifieddircontains more than 65534 files.
(PHP 4, PHP 5, PHP 7)
tmpfile — Creates a temporary file
Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle.
The file is automatically removed when closed (for example, by calling fclose(), or when there are no remaining references to the file handle returned by tmpfile()), or when the script ends.
If the script terminates unexpectedly, the temporary file may not be deleted.
Returns a file handle, similar to the one returned by
fopen(), for the new file or FALSE on failure.
Example #1 tmpfile() example
<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>
The above example will output:
writing to tempfile
(PHP 4, PHP 5, PHP 7)
touch — Sets access and modification time of file
$filename
[, int $time = time()
[, int $atime
]] ) : bool
Attempts to set the access and modification times of the file named in the
filename parameter to the value given in
time.
Note that the access time is always modified, regardless of the number
of parameters.
If the file does not exist, it will be created.
filenameThe name of the file being touched.
time
The touch time. If time is not supplied,
the current system time is used.
atime
If present, the access time of the given filename is set to
the value of atime. Otherwise, it is set to
the value passed to the time parameter.
If neither are present, the current system time is used.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.3.0 | It became possible to change the modification time of a directory under Windows. |
Example #1 touch() example
<?php
if (touch($filename)) {
echo $filename . ' modification time has been changed to present time';
} else {
echo 'Sorry, could not change modification time of ' . $filename;
}
?>
Example #2 touch() using the time parameter
<?php
// This is the touch time, we'll set it to one hour in the past.
$time = time() - 3600;
// Touch the file
if (!touch('some_file.txt', $time)) {
echo 'Whoops, something went wrong...';
} else {
echo 'Touched file with success';
}
?>
Note:
Note that time resolution may differ from one file system to another.
Prior to PHP 5.3.0 it was not possible to change the modification time of a directory with this function under Windows.
(PHP 4, PHP 5, PHP 7)
umask — Changes the current umask
$mask
] ) : int
umask() sets PHP's umask to
mask & 0777 and returns the old
umask. When PHP is being used as a server module, the umask
is restored when each request is finished.
maskThe new umask.
umask() without arguments simply returns the current umask otherwise the old umask is returned.
Example #1 umask() example
<?php
$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);
umask($old);
// Checking
if ($old != umask()) {
die('An error occurred while changing back the umask');
}
?>
Note:
Avoid using this function in multithreaded webservers. It is better to change the file permissions with chmod() after creating the file. Using umask() can lead to unexpected behavior of concurrently running scripts and the webserver itself because they all use the same umask.
(PHP 4, PHP 5, PHP 7)
unlink — Deletes a file
$filename
[, resource $context
] ) : bool
Deletes filename. Similar to the Unix C unlink()
function. An E_WARNING level error will be generated on
failure.
filenamePath to the file.
contextNote: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 7.3.0 | On Windows, it is now possible to unlink() files with handles in use, while formerly that would fail. However, it is still not possible to re-create the unlinked file, until all handles to it have been closed. |
Example #1 Basic unlink() usage
<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);
unlink('test.html');
?>
The inotify extension exposes the inotify functions inotify_init(), inotify_add_watch() and inotify_rm_watch().
As the C inotify_init() function returns a file descriptor, PHP's inotify_init() returns a stream resource, usable with standard stream functions, like stream_select(), stream_set_blocking() and fclose(). inotify_read() replaces the C way of reading inotify events.
This extension requires Linux 2.6.13 or newer, and a recent libC.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/inotify.
This extension has no configuration directives defined in php.ini.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
IN_ACCESS
(integer)
IN_MODIFY
(integer)
IN_ATTRIB
(integer)
IN_CLOSE_WRITE
(integer)
IN_CLOSE_NOWRITE
(integer)
IN_OPEN
(integer)
IN_MOVED_TO
(integer)
IN_MOVED_FROM
(integer)
IN_CREATE
(integer)
IN_DELETE
(integer)
IN_DELETE_SELF
(integer)
IN_MOVE_SELF
(integer)
IN_CLOSE
(integer)
IN_MOVE
(integer)
IN_ALL_EVENTS
(integer)
IN_UNMOUNT
(integer)
IN_Q_OVERFLOW
(integer)
IN_IGNORED
(integer)
IN_ISDIR
(integer)
IN_ONLYDIR
(integer)
IN_DONT_FOLLOW
(integer)
IN_MASK_ADD
(integer)
IN_ONESHOT
(integer)
Note: The events marked with an asterisk (*) above can occur for files in watched directories.
(PECL inotify >= 0.1.2)
inotify_add_watch — Add a watch to an initialized inotify instance
$inotify_instance
, string $pathname
, int $mask
) : int
inotify_add_watch() adds a new watch or modify an
existing watch for the file or directory specified in
pathname.
Using inotify_add_watch() on a watched object replaces
the existing watch. Using the IN_MASK_ADD constant
adds (OR) events to the existing watch.
inotify_instanceResource returned by inotify_init()
pathnameFile or directory to watch
maskEvents to watch for. See Predefined Constants.
The return value is a unique (inotify instance wide) watch descriptor.
(PECL inotify >= 0.1.2)
inotify_init — Initialize an inotify instance
Initialize an inotify instance for use with inotify_add_watch()
A stream resource or FALSE on error.
Example #1 Example usage of inotify
<?php
// Open an inotify instance
$fd = inotify_init();
// Watch __FILE__ for metadata changes (e.g. mtime)
$watch_descriptor = inotify_add_watch($fd, __FILE__, IN_ATTRIB);
// generate an event
touch(__FILE__);
// Read events
$events = inotify_read($fd);
print_r($events);
// The following methods allows to use inotify functions without blocking on inotify_read():
// - Using stream_select() on $fd:
$read = array($fd);
$write = null;
$except = null;
stream_select($read,$write,$except,0);
// - Using stream_set_blocking() on $fd
stream_set_blocking($fd, 0);
inotify_read($fd); // Does no block, and return false if no events are pending
// - Using inotify_queue_len() to check if event queue is not empty
$queue_len = inotify_queue_len($fd); // If > 0, inotify_read() will not block
// Stop watching __FILE__ for metadata changes
inotify_rm_watch($fd, $watch_descriptor);
// Close the inotify instance
// This may have closed all watches if this was not already done
fclose($fd);
?>
The above example will output something similar to:
array(
array(
'wd' => 1, // Equals $watch_descriptor
'mask' => 4, // IN_ATTRIB bit is set
'cookie' => 0, // unique id to connect related events (e.g.
// IN_MOVE_FROM and IN_MOVE_TO events)
'name' => '', // the name of a file (e.g. if we monitored changes
// in a directory)
),
);
(PECL inotify >= 0.1.2)
inotify_queue_len — Return a number upper than zero if there are pending events
$inotify_instance
) : intThis function allows to know if inotify_read() will block or not. If a number upper than zero is returned, there are pending events and inotify_read() will not block.
Returns a number upper than zero if there are pending events.
(PECL inotify >= 0.1.2)
inotify_read — Read events from an inotify instance
$inotify_instance
) : arrayRead inotify events from an inotify instance.
An array of inotify events or FALSE if no events was pending and
inotify_instance is non-blocking. Each event is an array with the following keys:
IN_MOVE_FROM
and IN_MOVE_TO)
(PECL inotify >= 0.1.2)
inotify_rm_watch — Remove an existing watch from an inotify instance
$inotify_instance
, int $watch_descriptor
) : bool
inotify_rm_watch() removes the watch
watch_descriptor from the inotify instance
inotify_instance.
inotify_instanceResource returned by inotify_init()
watch_descriptorWatch to remove from the instance
Returns TRUE on success or FALSE on failure.
This extension has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.
The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.
This extension is derived from Apache mod_mime_magic, which is itself based on the file command maintained by Ian F. Darwin. See the source code for further historic and copyright information.
No external libraries are needed to build this extension.
Mimetype extensions has been removed from PHP 5.3.0 in favor of Fileinfo.
You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.
Note:
This extension is not capable of handling the fully decorated magic file that generally comes with standard Linux distro's and is supposed to be used with recent versions of file command.
Note: Note to Win32 Users
In order to use this module on a Windows environment, you must set the path to the bundled magic.mime file in your php.ini.
Example #1 Setting the path to magic.mime
mime_magic.magicfile = "$PHP_INSTALL_DIR\magic.mime"Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| mime_magic.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0. |
| mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Available since PHP 4.3.0. |
Here's a short explanation of the configuration directives.
This extension has no resource types defined.
This extension has no constants defined.
The phdfs extensions is using PHP to manipulate Hadoop HDFS phdfs requires PHP 5.3 or greater. Earlier versions may not work. For a quick start guide, please refer to the Tutorials section.
PHP Version: PHP 5.3+
ZTS Enabled ( Thread Safety )
need to install hadoop
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/phdfs.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
(phdfs >= 0.1.0)
(phdfs >= 0.1.0)
phdfs::connect — Description
This function is currently not documented; only its argument list is available.
This function has no parameters.
Returns TRUE on success or FALSE on failure.
(phdfs >= 0.1.0)
phdfs::__construct — Description
$ip
, string $port
)
This function is currently not documented; only its argument list is available.
ip
port
(phdfs >= 0.1.0)
phdfs::copy — Description
$source_file
, string $destination_file
) : bool
This function is currently not documented; only its argument list is available.
source_file
destination_file
Returns TRUE on success or FALSE on failure.
(phdfs >= 0.1.0)
phdfs::create_directory — Description
$path
) : bool
This function is currently not documented; only its argument list is available.
path
Returns TRUE on success or FALSE on failure.
(phdfs >= 0.1.0)
phdfs::delete — Description
$path
) : bool
This function is currently not documented; only its argument list is available.
path
Returns TRUE on success or FALSE on failure.
(phdfs >= 0.1.0)
phdfs::__destruct — Description
This function is currently not documented; only its argument list is available.
This function has no parameters.
No value is returned.
(phdfs >= 0.1.0)
phdfs::disconnect — Description
This function is currently not documented; only its argument list is available.
This function has no parameters.
Returns TRUE on success or FALSE on failure.
(phdfs>= 0.1.0)
phdfs::exists — Description
$path
) : bool
This function is currently not documented; only its argument list is available.
path
Returns TRUE on success or FALSE on failure.
(phdfs >= 0.1.0)
phdfs::file_info — Description
$path
) : array
This function is currently not documented; only its argument list is available.
path
Returns array on success or FALSE on failure.
(phdfs >= 0.1.0)
phdfs::list_directory — Description
$path
[, int $level = 0
] ) : array
This function is currently not documented; only its argument list is available.
path
level
Returns array on success or FALSE on failure.
(phdfs >= 0.1.0)
phdfs::read — Description
$path
[, int $length = 0
] ) : string
This function is currently not documented; only its argument list is available.
path
length
(phdfs >= 0.1.0)
phdfs::rename — Description
$old_path
, string $new_path
) : bool
This function is currently not documented; only its argument list is available.
old_path
new_path
Returns TRUE on success or FALSE on failure.
(phdfs >= 0.1.0)
phdfs::tell — Description
$path
[, int $read_length = 1024
] ) : int
This function is currently not documented; only its argument list is available.
path
read_length
(phdfs >= 0.1.0)
phdfs::write — Description
$path
, string $buffer
[, int $mode = 0
] ) : bool
This function is currently not documented; only its argument list is available.
path
buffer
mode
Returns TRUE on success or FALSE on failure.
This extension allows changing the current process', and thread, name on Linux and *BSD systems. This is useful when using pcntl_fork() to identify running processes in process list
Nothing special.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/proctitle.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
This extension has no constants defined.
(PECL proctitle >= 0.1.0)
setproctitle — Set the process title
$title
) : voidSets the process title of the current process.
titleThe title to use as the process title.
No value is returned.
Example #1 setproctitle() example
Running the example below will change the process title (visible with
ps a for example).
<?php
setproctitle("myscript");
?>
The above example will output something similar to:
$ ps a
PID TTY STAT TIME COMMAND
1168 pts/3 S 0:00 myscript
(PECL proctitle >= 0.1.2)
setthreadtitle — Set the thread title
$title
) : boolSets the thread title.
titleThe title to use as the thread title.
Returns TRUE on success or FALSE on failure.
Example #1 setthreadtitle() example
Running the example below will change the thread title (visible with
ps c for example).
<?php
setthreadtitle("myscript");
?>
The above example will output something similar to:
$ ps c
PID TTY STAT TIME COMMAND
1178 pts/3 S 0:00 myscript
The xattr extension allows for the manipulation of extended attributes on a filesystem.
To use xattr, you will need libattr installed. It is available at » http://savannah.nongnu.org/projects/attr/.
Note:
These functions only work on filesystems that support extended attributes, and have them enabled at mount time. Some common filesystems that support extended attributes are ext2, ext3, reiserfs, jfs, and xfs.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/xattr.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
XATTR_ROOT
(integer)
XATTR_DONTFOLLOW
(integer)
XATTR_CREATE
(integer)
XATTR_REPLACE
(integer)
(PECL xattr >= 0.9.0)
xattr_get — Get an extended attribute
$filename
, string $name
[, int $flags = 0
] ) : stringThis function gets the value of an extended attribute of a file.
Extended attributes have two different namespaces: user
and root. The user namespace is available to all users, while the root namespace
is available only to users with root privileges. xattr operates on the user
namespace by default, but this can be changed with the
flags parameter.
filenameThe file from which we get the attribute.
nameThe name of the attribute.
flags
XATTR_DONTFOLLOW |
Do not follow the symbolic link but operate on symbolic link itself. |
XATTR_ROOT |
Set attribute in root (trusted) namespace. Requires root privileges. |
Returns a string containing the value or FALSE if the attribute doesn't
exist.
Example #1 Checks if system administrator has signed the file
<?php
$file = '/usr/local/sbin/some_binary';
$signature = xattr_get($file, 'Root signature', XATTR_ROOT);
/* ... check if $signature is valid ... */
?>
(PECL xattr >= 0.9.0)
xattr_list — Get a list of extended attributes
$filename
[, int $flags = 0
] ) : arrayThis functions gets a list of names of extended attributes of a file.
Extended attributes have two different namespaces: user
and root. The user namespace is available to all users, while the root namespace
is available only to users with root privileges. xattr operates on the user
namespace by default, but this can be changed with the
flags parameter.
filenameThe path of the file.
flags
XATTR_DONTFOLLOW |
Do not follow the symbolic link but operate on symbolic link itself. |
XATTR_ROOT |
Set attribute in root (trusted) namespace. Requires root privileges. |
This function returns an array with names of extended attributes.
Example #1 Prints names of all extended attributes of file
<?php
$file = 'some_file';
$root_attributes = xattr_list($file, XATTR_ROOT);
$user_attributes = xattr_list($file);
echo "Root attributes: \n";
foreach ($root_attributes as $attr_name) {
printf("%s\n", $attr_name);
}
echo "\n User attributes: \n";
foreach ($attributes as $attr_name) {
printf("%s\n", $attr_name);
}
?>
(PECL xattr >= 0.9.0)
xattr_remove — Remove an extended attribute
$filename
, string $name
[, int $flags = 0
] ) : boolThis function removes an extended attribute of a file.
Extended attributes have two different namespaces: user
and root. The user namespace is available to all users, while the root namespace
is available only to users with root privileges. xattr operates on the user
namespace by default, but this can be changed with the
flags parameter.
filenameThe file from which we remove the attribute.
nameThe name of the attribute to remove.
flags
XATTR_DONTFOLLOW |
Do not follow the symbolic link but operate on symbolic link itself. |
XATTR_ROOT |
Set attribute in root (trusted) namespace. Requires root privileges. |
Returns TRUE on success or FALSE on failure.
Example #1 Removes all extended attributes of a file
<?php
$file = 'some_file';
$attributes = xattr_list($file);
foreach ($attributes as $attr_name) {
xattr_remove($file, $attr_name);
}
?>
(PECL xattr >= 0.9.0)
xattr_set — Set an extended attribute
$filename
, string $name
, string $value
[, int $flags = 0
] ) : boolThis function sets the value of an extended attribute of a file.
Extended attributes have two different namespaces: user
and root. The user namespace is available to all users, while the root namespace
is available only to users with root privileges. xattr operates on the user
namespace by default, but this can be changed with the
flags parameter.
filenameThe file in which we set the attribute.
name
The name of the extended attribute. This attribute will be created if
it doesn't exist or replaced otherwise. You can change this behaviour
by using the flags parameter.
valueThe value of the attribute.
flags
XATTR_CREATE |
Function will fail if extended attribute already exists. |
XATTR_REPLACE |
Function will fail if extended attribute doesn't exist. |
XATTR_DONTFOLLOW |
Do not follow the symbolic link but operate on symbolic link itself. |
XATTR_ROOT |
Set attribute in root (trusted) namespace. Requires root privileges. |
Returns TRUE on success or FALSE on failure.
Example #1 Sets extended attributes on .wav file
<?php
$file = 'my_favourite_song.wav';
xattr_set($file, 'Artist', 'Someone');
xattr_set($file, 'My ranking', 'Good');
xattr_set($file, 'Listen count', '34');
/* ... other code ... */
printf("You've played this song %d times", xattr_get($file, 'Listen count'));
?>
(PECL xattr >= 1.0.0)
xattr_supported — Check if filesystem supports extended attributes
$filename
[, int $flags = 0
] ) : boolThis functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.
filenameThe path of the tested file.
flags
XATTR_DONTFOLLOW |
Do not follow the symbolic link but operate on symbolic link itself. |
This function returns TRUE if filesystem supports extended attributes,
FALSE if it doesn't and NULL if it can't be determined (for example
wrong path or lack of permissions to file).
Example #1 xattr_supported() example
The following code checks if we can use extended attributes.
<?php
$file = 'some_file';
if (xattr_supported($file)) {
/* ... make use of some xattr_* functions ... */
}
?>
xdiff extension enables you to create and apply patch files containing differences between different revisions of files.
This extension supports two modes of operation - on strings and on files, as well as two different patch formats - unified and binary. Unified patches are excellent for text files as they are human-readable and easy to review. For binary files like archives or images, binary patches will be adequate choice as they are binary safe and handle non-printable characters well.
Starting from version 1.5.0 there are two different sets of functions for generating binary patches. New functions - xdiff_string_rabdiff() and xdiff_file_rabdiff() generate output compatible with older functions but are typically faster and generate smaller results. For more details about methods of generating binary patches and differences between them, please check » libxdiff website.
This extension uses libxdiff to implement these functions. Please see » http://www.xmailserver.org/xdiff-lib.html for more information.
To use xdiff, you will need libxdiff installed, available on the libxdiff homepage » http://www.xmailserver.org/xdiff-lib.html.
Note:
You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/xdiff.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
XDIFF_PATCH_NORMAL
(integer)
XDIFF_PATCH_REVERSE
(integer)
(PECL xdiff >= 1.5.0)
xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
$file
) : int
Returns a size of a result file that would be created after applying binary patch from file
file to the original file.
fileThe path to the binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.
Returns the size of file that would be created.
Example #1 xdiff_file_bdiff_size() example
The following code applies reads a size of file that would be created after applying a binary diff.
<?php
$length = xdiff_string_bdiff_size('file.bdiff');
echo "Resulting file will be $length bytes long";
?>
(PECL xdiff >= 1.5.0)
xdiff_file_bdiff — Make binary diff of two files
$old_file
, string $new_file
, string $dest
) : boolMakes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().
old_filePath to the first file. This file acts as "old" file.
new_filePath to the second file. This file acts as "new" file.
destPath of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.
Returns TRUE on success or FALSE on failure.
Example #1 xdiff_file_bdiff() example
The following code makes binary diff of two archives.
<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';
xdiff_file_bdiff($old_version, $new_version, 'my_script.bdiff');
?>
Note:
Both files will be loaded into memory so ensure that your memory_limit is set high enough.
(PECL xdiff >= 1.5.0)
xdiff_file_bpatch — Patch a file with a binary diff
$file
, string $patch
, string $dest
) : bool
Patches a file with a binary
patch and stores the result in a file dest.
This function accepts patches created both via xdiff_file_bdiff()
and xdiff_file_rabdiff() functions or their string counterparts.
fileThe original file.
patchThe binary patch file.
destPath of the resulting file.
Returns TRUE on success or FALSE on failure.
Example #1 xdiff_file_bpatch() example
The following code applies binary diff to a file.
<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';
$result = xdiff_file_bpatch($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
echo "File patched";
} else {
echo "File couldn't be patched";
}
?>
Note:
Both files (
fileandpatch) will be loaded into memory so ensure that your memory_limit is set high enough.
(PECL xdiff >= 0.2.0)
xdiff_file_diff_binary — Alias of xdiff_file_bdiff
$old_file
, string $new_file
, string $dest
) : boolMakes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch().
Starting with version 1.5.0 this function is an alias of xdiff_file_bdiff().
old_filePath to the first file. This file acts as "old" file.
new_filePath to the second file. This file acts as "new" file.
destPath of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.
Returns TRUE on success or FALSE on failure.
Example #1 xdiff_file_diff_binary() example
The following code makes binary diff of two archives.
<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';
xdiff_file_diff_binary($old_version, $new_version, 'my_script.bdiff');
?>
Note:
Both files will be loaded into memory so ensure that your memory_limit is set high enough.
(PECL xdiff >= 0.2.0)
xdiff_file_diff — Make unified diff of two files
$old_file
, string $new_file
, string $dest
[, int $context = 3
[, bool $minimal = FALSE
]] ) : bool
Makes an unified diff containing differences between old_file and
new_file and stores it in dest file. The
resulting file is human-readable. An optional context parameter
specifies how many lines of context should be added around each change.
Setting minimal parameter to true will result in outputting the shortest
patch file possible (can take a long time).
old_filePath to the first file. This file acts as "old" file.
new_filePath to the second file. This file acts as "new" file.
destPath of the resulting patch file.
contextIndicates how many lines of context you want to include in diff result.
minimal
Set this parameter to TRUE if you want to minimalize size of the result
(can take a long time).
Returns TRUE on success or FALSE on failure.
Example #1 xdiff_file_diff() example
The following code makes unified diff of two php files with context length of 2.
<?php
$old_version = 'my_script.php';
$new_version = 'my_new_script.php';
xdiff_file_diff($old_version, $new_version, 'my_script.diff', 2);
?>
Note:
This function doesn't work well with binary files. To make diff of binary files use xdiff_file_bdiff()/xdiff_file_rabdiff() function.
(PECL xdiff >= 0.2.0)
xdiff_file_merge3 — Merge 3 files into one
$old_file
, string $new_file1
, string $new_file2
, string $dest
) : mixed
Merges three files into one and stores the result in a file dest.
The old_file is an original version while new_file1
and new_file2 are modified versions of an original.
old_filePath to the first file. It acts as "old" file.
new_file1
Path to the second file. It acts as modified version of old_file.
new_file2
Path to the third file. It acts as modified version of old_file.
dest
Path of the resulting file, containing merged changed from both new_file1 and
new_file2.
Returns TRUE if merge was successful, string with rejected chunks if
it was not or FALSE if an internal error happened.
Example #1 xdiff_file_merge3() example
The following code merges three files into one.
<?php
$old_version = 'original_script.php';
$fix1 = 'script_with_fix1.php';
$fix2 = 'script_with_fix2.php';
$errors = xdiff_file_merge3($old_version, $fix1, $fix2, 'fixed_script.php');
if (is_string($errors)) {
echo "Rejects:\n";
echo $errors;
}
?>
(PECL xdiff >= 0.2.0)
xdiff_file_patch_binary — Alias of xdiff_file_bpatch
$file
, string $patch
, string $dest
) : bool
Patches a file with a binary
patch and stores the result in a file dest.
This function accepts patches created both via xdiff_file_bdiff()
or xdiff_file_rabdiff() functions or their string counterparts.
Starting with version 1.5.0 this function is an alias of xdiff_file_bpatch().
fileThe original file.
patchThe binary patch file.
destPath of the resulting file.
Returns TRUE on success or FALSE on failure.
Example #1 xdiff_file_patch_binary() example
The following code applies binary diff to a file.
<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';
$result = xdiff_file_patch_binary($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
echo "File patched";
} else {
echo "File couldn't be patched";
}
?>
Note:
Both files (
fileandpatch) will be loaded into memory so ensure that your memory_limit is set high enough.
(PECL xdiff >= 0.2.0)
xdiff_file_patch — Patch a file with an unified diff
$file
, string $patch
, string $dest
[, int $flags = DIFF_PATCH_NORMAL
] ) : mixed
Patches a file with a patch and stores the result in a file.
patch has to be an unified diff created by
xdiff_file_diff()/xdiff_string_diff() function.
An optional flags parameter specifies mode of operation.
fileThe original file.
patchThe unified patch file. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.
destPath of the resulting file.
flags
Can be either XDIFF_PATCH_NORMAL (default mode,
normal patch) or XDIFF_PATCH_REVERSE (reversed
patch).
Starting from version 1.5.0, you can also use binary OR to enable
XDIFF_PATCH_IGNORESPACE flag.
Returns FALSE if an internal error happened, string with rejected
chunks if patch couldn't be applied or TRUE if patch has been successfully applied.
Example #1 xdiff_file_patch() example
The following code applies unified diff to a file.
<?php
$old_version = 'my_script-1.0.php';
$patch = 'my_script.patch';
$errors = xdiff_file_patch($old_version, $patch, 'my_script-1.1.php');
if (is_string($errors)) {
echo "Rejects:\n";
echo $errors;
}
?>
Example #2 Patch reversing example
The following code reverses a patch.
<?php
$new_version = 'my_script-1.1.php';
$patch = 'my_script.patch';
$errors = xdiff_file_patch($new_version, $patch, 'my_script-1.0.php', XDIFF_PATCH_REVERSE);
if (is_string($errors)) {
echo "Rejects:\n";
echo $errors;
}
?>
(PECL xdiff >= 1.5.0)
xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
$old_file
, string $new_file
, string $dest
) : boolMakes a binary diff of two files and stores the result in a patch file. The difference between this function and xdiff_file_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().
For more details about differences between algorithm used please check » libxdiff website.
old_filePath to the first file. This file acts as "old" file.
new_filePath to the second file. This file acts as "new" file.
destPath of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.
Returns TRUE on success or FALSE on failure.
Example #1 xdiff_file_rabdiff() example
The following code makes binary diff of two archives.
<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';
xdiff_file_rabdiff($old_version, $new_version, 'my_script.bdiff');
?>
Note:
Both files will be loaded into memory so ensure that your memory_limit is set high enough.
(PECL xdiff >= 1.5.0)
xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
$patch
) : int
Returns a size of a result file that would be created after applying binary patch to
the original file.
patchThe binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.
Returns the size of file that would be created.
Example #1 xdiff_string_bdiff_size() example
The following code applies reads a size of file that would be created after applying a binary diff.
<?php
$binary_patch = file_get_contents('file.bdiff');
$length = xdiff_string_bdiff_size($binary_patch);
echo "Resulting file will be $length bytes long";
?>
(PECL xdiff >= 1.5.0)
xdiff_string_bdiff — Make binary diff of two strings
$old_data
, string $new_data
) : stringMakes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().
old_dataFirst string with binary data. It acts as "old" data.
new_dataSecond string with binary data. It acts as "new" data.
Returns string with binary diff containing differences between "old" and "new"
data or FALSE if an internal error occurred.
(PECL xdiff >= 1.5.0)
xdiff_string_bpatch — Patch a string with a binary diff
$str
, string $patch
) : string
Patches a string str with a binary patch.
This function accepts patches created both via xdiff_string_bdiff()
and xdiff_string_rabdiff() functions or their file counterparts.
strThe original binary string.
patchThe binary patch string.
Returns the patched string, or FALSE on error.
(PECL xdiff >= 0.2.0)
xdiff_string_diff_binary — Alias of xdiff_string_bdiff
Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().
Starting with version 1.5.0 this function is an alias of xdiff_string_bdiff().
old_dataFirst string with binary data. It acts as "old" data.
new_dataSecond string with binary data. It acts as "new" data.
Returns string with result or FALSE if an internal error happened.
(PECL xdiff >= 0.2.0)
xdiff_string_diff — Make unified diff of two strings
$old_data
, string $new_data
[, int $context = 3
[, bool $minimal = FALSE
]] ) : string
Makes an unified diff containing differences between old_data string and
new_data string and returns it. The resulting diff is human-readable.
An optional context parameter specifies how many lines of context should be
added around each change. Setting minimal parameter
to true will result in outputting the shortest patch file possible (can take a long time).
old_dataFirst string with data. It acts as "old" data.
new_dataSecond string with data. It acts as "new" data.
contextIndicates how many lines of context you want to include in the diff result.
minimal
Set this parameter to TRUE if you want to minimalize the size of the
result (can take a long time).
Returns string with resulting diff or FALSE if an internal error happened.
Example #1 xdiff_string_diff() example
The following code makes unified diff of two articles.
<?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_REQUEST['article']; /* Let's say that someone pasted a new article to html form */
$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
echo "Differences between two articles:\n";
echo $diff;
}
?>
Note:
This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_bdiff()/xdiff_string_rabdiff().
(PECL xdiff >= 0.2.0)
xdiff_string_merge3 — Merge 3 strings into one
$old_data
, string $new_data1
, string $new_data2
[, string &$error
] ) : mixed
Merges three strings into one and returns the result.
The old_data is an original version of data
while new_data1 and new_data2 are modified
versions of an original. An optional error is used to pass any
rejected parts during merging process.
old_dataFirst string with data. It acts as "old" data.
new_data1
Second string with data. It acts as modified version of old_data.
new_data2
Third string with data. It acts as modified version of old_data.
errorIf provided then rejected parts are stored inside this variable.
Returns the merged string, FALSE if an internal error happened, or TRUE
if merged string is empty.
(PECL xdiff >= 0.2.0)
xdiff_string_patch_binary — Alias of xdiff_string_bpatch
$str
, string $patch
) : string
Patches a string str with a binary patch.
This function accepts patches created both via xdiff_string_bdiff()
and xdiff_string_rabdiff() functions or their file counterparts.
Starting with version 1.5.0 this function is an alias of xdiff_string_bpatch().
strThe original binary string.
patchThe binary patch string.
Returns the patched string, or FALSE on error.
(PECL xdiff >= 0.2.0)
xdiff_string_patch — Patch a string with an unified diff
$str
, string $patch
[, int $flags
[, string &$error
]] ) : string
Patches a str string with an unified patch in patch parameter
and returns the result. patch has to be an unified diff created by
xdiff_file_diff()/xdiff_string_diff() function.
An optional flags parameter specifies mode of operation. Any
rejected parts of the patch will be stored inside error variable if
it is provided.
strThe original string.
patchThe unified patch string. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.
flags
flags can be either
XDIFF_PATCH_NORMAL (default mode, normal patch)
or XDIFF_PATCH_REVERSE (reversed patch).
Starting from version 1.5.0, you can also use binary OR to enable
XDIFF_PATCH_IGNORESPACE flag.
errorIf provided then rejected parts are stored inside this variable.
Returns the patched string, or FALSE on error.
Example #1 xdiff_string_patch() example
The following code applies changes to some article.
<?php
$old_article = file_get_contents('./old_article.txt');
$diff = $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */
$errors = '';
$new_article = xdiff_string_patch($old_article, $diff, XDIFF_PATCH_NORMAL, $errors);
if (is_string($new_article)) {
echo "New article:\n";
echo $new_article;
}
if (strlen($errors)) {
echo "Rejects: \n";
echo $errors;
}
?>
(PECL xdiff >= 1.5.0)
xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
Makes a binary diff of two strings and returns the result. The difference between this function and xdiff_string_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().
For more details about differences between algorithm used please check » libxdiff website.
old_dataFirst string with binary data. It acts as "old" data.
new_dataSecond string with binary data. It acts as "new" data.
Returns string with binary diff containing differences between "old" and "new"
data or FALSE if an internal error occurred.
Enchant is the PHP binding for the » Enchant library. Enchant steps in to provide uniformity and conformity on top of all spelling libraries, and implement certain features that may be lacking in any individual provider library. Everything should "just work" for any and every definition of "just working."
Enchant supports the following backends:
Aspell/Pspell (intends to replace Ispell)
Ispell (old as sin, could be interpreted as a defacto standard)
MySpell/Hunspell (an OOo projects, also used by Mozilla)
Uspell (primarily Yiddish, Hebrew, and Eastern European languages - hosted in AbiWord's CVS under the module "uspell")
Hspell (Hebrew)
AppleSpell (Mac OSX)
This version uses the functions of the » Enchant library by Dom Lachowicz. You need Enchant 1.2.4 or later. Enchant 2.0.0 or later is not yet supported.
Enchant also requires » Glib 2.6 or greater. Pre-compiled Windows libraries are available from » http://ftp.gnome.org/pub/gnome/binaries/win32/glib/.
This extension is bundled with PHP as of PHP 5.3.0. Before this time, enchant was a PECL extension. Users of versions prior to 5.3.0 may use the » PECL extension.
Provided the required libraries are installed, users of PHP 5.3.0 or later may enable enchant by adding the --with-enchant[=dir] option when compiling PHP.
This extension has no configuration directives defined in php.ini.
There are two types of resources in this extension. The first one is the broker (backends manager) and the second is for the dictionary.
ENCHANT_MYSPELL
(integer)
ENCHANT_ISPELL
(integer)
Example #1 Enchant Usage Example
<?php
$tag = 'en_US';
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
if (enchant_broker_dict_exists($r,$tag)) {
$d = enchant_broker_request_dict($r, $tag);
$dprovides = enchant_dict_describe($d);
echo "dictionary $tag provides:\n";
$wordcorrect = enchant_dict_check($d, "soong");
print_r($dprovides);
if (!$wordcorrect) {
$suggs = enchant_dict_suggest($d, "soong");
echo "Suggestions for 'soong':";
print_r($suggs);
}
enchant_broker_free_dict($d);
} else {
}
enchant_broker_free($r);
?>
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0)
enchant_broker_describe — Enumerates the Enchant providers
$broker
) : arrayEnumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().
brokerBroker resource
Returns an array of available Enchant providers with their details, or FALSE on failure.
Example #1 List the backends provided by the given broker
<?php
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);
?>
The above example will output something similar to:
Current broker provides the following backend(s):
Array
(
[0] => Array
(
[name] => aspell
[desc] => Aspell Provider
[file] => /usr/lib/enchant/libenchant_aspell.so
)
[1] => Array
(
[name] => hspell
[desc] => Hspell Provider
[file] => /usr/lib/enchant/libenchant_hspell.so
)
[2] => Array
(
[name] => ispell
[desc] => Ispell Provider
[file] => /usr/lib/enchant/libenchant_ispell.so
)
[3] => Array
(
[name] => myspell
[desc] => Myspell Provider
[file] => /usr/lib/enchant/libenchant_myspell.so
)
)
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
$broker
, string $tag
) : boolTells if a dictionary exists or not, using a non-empty tags
brokerBroker resource
tagnon-empty tag in the LOCALE format, ex: us_US, ch_DE, etc.
Returns TRUE when the tag exist or FALSE when not.
Example #1 A enchant_broker_dict_exists() example
<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
echo $tag . " dictionary found.\n";
}
?>
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_broker_free_dict — Free a dictionary resource
$dict
) : boolFree a dictionary resource.
dictDictionary resource.
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_broker_free — Free the broker resource and its dictionaries
$broker
) : boolFree a broker resource with all its dictionaries.
brokerBroker resource
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.3.1, PHP 7, PECL enchant >= 1.0.1)
enchant_broker_get_dict_path — Get the directory path for a given backend
$broker
, int $dict_type
) : boolGet the directory path for a given backend.
brokerBroker resource.
dict_type
The type of the dictionaries, i.e. ENCHANT_MYSPELL
or ENCHANT_ISPELL.
Returns the path of the dictionary directory on
success or FALSE on failure.
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_broker_get_error — Returns the last error of the broker
$broker
) : stringReturns the last error which occurred in this broker.
brokerBroker resource.
Return the msg string if an error was found or FALSE
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_broker_init — Create a new broker object capable of requesting
Returns a broker resource on success or FALSE.
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 1.0.1)
enchant_broker_list_dicts — Returns a list of available dictionaries
Returns a list of available dictionaries with their details.
brokerBroker resource
Returns an array of available dictionaries with their details, or FALSE on failure.
Example #1 List all available dictionaries for one broker
<?php
$r = enchant_broker_init();
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
?>
The above example will output something similar to:
Array
(
[0] => Array
(
[lang_tag] => de
[provider_name] => aspell
[provider_desc] => Aspell Provider
[provider_file] => /usr/lib/enchant/libenchant_aspell.so
)
[1] => Array
(
[lang_tag] => de_DE
[provider_name] => aspell
[provider_desc] => Aspell Provider
[provider_file] => /usr/lib/enchant/libenchant_aspell.so
)
[3] => Array
(
[lang_tag] => en
[provider_name] => aspell
[provider_desc] => Aspell Provider
[provider_file] => /usr/lib/enchant/libenchant_aspell.so
)
[4] => Array
(
[lang_tag] => en_GB
[provider_name] => aspell
[provider_desc] => Aspell Provider
[provider_file] => /usr/lib/enchant/libenchant_aspell.so
)
[5] => Array
(
[lang_tag] => en_US
[provider_name] => aspell
[provider_desc] => Aspell Provider
[provider_file] => /usr/lib/enchant/libenchant_aspell.so
)
[6] => Array
(
[lang_tag] => hi_IN
[provider_name] => myspell
[provider_desc] => Myspell Provider
[provider_file] => /usr/lib/enchant/libenchant_myspell.so
)
)
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_broker_request_dict — Create a new dictionary using a tag
$broker
, string $tag
) : resourcecreate a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)
brokerBroker resource
tagA tag describing the locale, for example en_US, de_DE
Returns a dictionary resource on success or FALSE on failure.
Example #1 A enchant_broker_request_dict() example
Check if a dictionary exists using enchant_broker_dict_exists() and request it.
<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
$dict = enchant_broker_request_dict($r, $tag);
}
?>
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_broker_request_pwl_dict — Creates a dictionary using a PWL file
$broker
, string $filename
) : resourceCreates a dictionary using a PWL file. A PWL file is personal word file one word per line.
brokerBroker resource
filenamePath to the PWL file. If there is no such file, a new one will be created if possible.
Returns a dictionary resource on success or FALSE on failure.
(PHP 5 >= 5.3.1, PHP 7, PECL enchant >= 1.0.1)
enchant_broker_set_dict_path — Set the directory path for a given backend
$broker
, int $dict_type
, string $value
) : boolSet the directory path for a given backend.
brokerBroker resource.
dict_type
The type of the dictionaries, i.e. ENCHANT_MYSPELL
or ENCHANT_ISPELL.
valueThe path of the dictionary directory.
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language
$broker
, string $tag
, string $ordering
) : boolDeclares a preference of dictionaries to use for the language described/referred to by 'tag'. The ordering is a comma delimited list of provider names. As a special exception, the "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.
brokerBroker resource
tagLanguage tag. The special "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.
orderingComma delimited list of provider names
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_dict_add_to_personal — Add a word to personal word list
$dict
, string $word
) : voidAdd a word to personal word list of the given dictionary.
dictDictionary resource
wordThe word to add
Returns TRUE on success or FALSE on failure.
Example #1 Adding a word to a PWL
<?php
$filename = './my_word_list.pwl';
$word = 'Supercalifragilisticexpialidocious';
$broker = enchant_broker_init();
$dict = enchant_broker_request_pwl_dict($broker, $filename);
enchant_dict_add_to_personal($dict, $word);
enchant_broker_free($broker);
?>
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_dict_add_to_session — Add 'word' to this spell-checking session
$dict
, string $word
) : voidAdd a word to the given dictionary. It will be added only for the active spell-checking session.
dictDictionary resource
wordThe word to add
No value is returned.
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_dict_check — Check whether a word is correctly spelled or not
$dict
, string $word
) : bool
If the word is correctly spelled return TRUE, otherwise return FALSE
dictDictionary resource
wordThe word to check
Returns TRUE if the word is spelled correctly, FALSE if not.
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_dict_describe — Describes an individual dictionary
dictDictionary resource
Returns TRUE on success or FALSE on failure.
Example #1 A enchant_dict_describe() example
Check if a dictionary exists using enchant_broker_dict_exists() and show the detail of it.
<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
$dict = enchant_broker_request_dict($r, $tag);
$dict_details = enchant_dict_describe($dict);
print_r($dict_details);
}
?>
The above example will output something similar to:
Array
(
[lang] => en_US
[name] => aspell
[desc] => Aspell Provider
[file] => /usr/lib/enchant/libenchant_aspell.so
)
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_dict_get_error — Returns the last error of the current spelling-session
$dict
) : stringReturns the last error of the current spelling-session
dictDictinaray resource
Returns the error message as string or FALSE if no error occurred.
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_dict_is_in_session — Whether or not 'word' exists in this spelling-session
$dict
, string $word
) : boolTells whether or not a word already exists in the current session.
dictDictionary resource
wordThe word to lookup
Returns TRUE if the word exists or FALSE
(PHP 5 >= 5.3.0, PHP 7, PECL enchant:0.2.0-1.0.1)
enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions
$dict
, string $word
[, array &$suggestions
] ) : bool
If the word is correctly spelled return TRUE, otherwise return FALSE, if suggestions variable
is provided, fill it with spelling alternatives.
dictDictionary resource
wordThe word to check
suggestionsIf the word is not correctly spelled, this variable will contain an array of suggestions.
Returns TRUE if the word is correctly spelled or FALSE
Example #1 A enchant_dict_quick_check() example
<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
$d = enchant_broker_request_dict($r, $tag);
enchant_dict_quick_check($d, 'soong', $suggs);
print_r($suggs);
}
?>
The above example will output something similar to:
Array
(
[0] => song
[1] => snog
[2] => soon
[3] => Sang
[4] => Sung
[5] => sang
[6] => sung
[7] => sponge
[8] => spongy
[9] => snag
[10] => snug
[11] => sonic
[12] => sing
[13] => songs
[14] => Son
[15] => Sonja
[16] => Synge
[17] => son
[18] => Sejong
[19] => sarong
[20] => sooner
[21] => Sony
[22] => sown
[23] => scone
[24] => song's
)
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_dict_store_replacement — Add a correction for a word
$dict
, string $mis
, string $cor
) : voidAdd a correction for 'mis' using 'cor'. Notes that you replaced @mis with @cor, so it's possibly more likely that future occurrences of @mis will be replaced with @cor. So it might bump @cor up in the suggestion list.
dictDictionary resource
misThe work to fix
corThe correct word
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )
enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met
$dict
, string $word
) : array
dictDictionary resource
wordWord to use for the suggestions.
Will returns an array of suggestions if the word is bad spelled.
Example #1 A enchant_dict_suggest() example
<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
$d = enchant_broker_request_dict($r, $tag);
$wordcorrect = enchant_dict_check($d, "soong");
if (!$wordcorrect) {
$suggs = enchant_dict_suggest($d, "soong");
echo "Suggestions for 'soong':";
print_r($suggs);
}
enchant_broker_free_dict($d);
}
enchant_broker_free($r);
?>
This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/fribidi.
In order to use these functions you must compile PHP with Fribidi support by using the --with-fribidi[=DIR] configure option.
Windows users will enable php_fribidi.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
FRIBIDI_CHARSET_UTF8
(integer)
FRIBIDI_CHARSET_8859_6
(integer)
FRIBIDI_CHARSET_8859_8
(integer)
FRIBIDI_CHARSET_CP1255
(integer)
FRIBIDI_CHARSET_CP1256
(integer)
FRIBIDI_CHARSET_ISIRI_3342
(integer)
FRIBIDI_CHARSET_CAP_RTL
(integer)
FRIBIDI_RTL
(integer)
FRIBIDI_LTR
(integer)
FRIBIDI_AUTO
(integer)
(PHP 4 >= 4.0.4 and PHP 4 <= 4.1.0, PECL fribidi >= 1.0)
fribidi_log2vis — Convert a logical string to a visual one
$str
, string $direction
, int $charset
) : stringConverts a logical string to a visual one.
strThe logical string.
direction
One of FRIBIDI_RTL,
FRIBIDI_LTR or FRIBIDI_AUTO.
charset
One of the FRIBIDI_CHARSET_XXX constants.
Returns the visual string on success or FALSE on failure.
Gender PHP extension is a port of the gender.c program originally written by Joerg Michael. The main purpose is to find out the gender of firstnames. The current database contains >40000 firstnames from 54 countries.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/gender.
A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/gender/.
Gender class usage example.
Example #1 Usage example.
<?php
namespace Gender;
$gender = new Gender;
$name = "Milene";
$country = Gender::FRANCE;
$result = $gender->get($name, $country);
$data = $gender->country($country);
switch($result) {
case Gender::IS_FEMALE:
printf("The name %s is female in %s\n", $name, $data['country']);
break;
case Gender::IS_MOSTLY_FEMALE:
printf("The name %s is mostly female in %s\n", $name, $data['country']);
break;
case Gender::IS_MALE:
printf("The name %s is male in %s\n", $name, $data['country']);
break;
case Gender::IS_MOSTLY_MALE:
printf("The name %s is mostly male in %s\n", $name, $data['country']);
break;
case Gender::IS_UNISEX_NAME:
printf("The name %s is unisex in %s\n", $name, $data['country']);
break;
case Gender::IS_A_COUPLE:
printf("The name %s is both male and female in %s\n", $name, $data['country']);
break;
case Gender::NAME_NOT_FOUND:
printf("The name %s was not found for %s\n", $name, $data['country']);
break;
case Gender::ERROR_IN_NAME:
echo "There is an error in the given name!\n";
break;
default:
echo "An error occurred!\n";
break;
}
(PECL gender >= 0.6.0)
Gender\Gender::IS_FEMALEGender\Gender::IS_MOSTLY_FEMALEGender\Gender::IS_MALEGender\Gender::IS_MOSTLY_MALEGender\Gender::IS_UNISEX_NAMEGender\Gender::IS_A_COUPLEGender\Gender::NAME_NOT_FOUNDGender\Gender::ERROR_IN_NAMEGender\Gender::ANY_COUNTRYGender\Gender::BRITAINGender\Gender::IRELANDGender\Gender::USAGender\Gender::SPAINGender\Gender::PORTUGALGender\Gender::ITALYGender\Gender::MALTAGender\Gender::FRANCEGender\Gender::BELGIUMGender\Gender::LUXEMBOURGGender\Gender::NETHERLANDSGender\Gender::GERMANYGender\Gender::EAST_FRISIAGender\Gender::AUSTRIAGender\Gender::SWISSGender\Gender::ICELANDGender\Gender::DENMARKGender\Gender::NORWAYGender\Gender::SWEDENGender\Gender::FINLANDGender\Gender::ESTONIAGender\Gender::LATVIAGender\Gender::LITHUANIAGender\Gender::POLANDGender\Gender::CZECH_REPGender\Gender::SLOVAKIAGender\Gender::HUNGARYGender\Gender::ROMANIAGender\Gender::BULGARIAGender\Gender::BOSNIAGender\Gender::CROATIAGender\Gender::KOSOVOGender\Gender::MACEDONIAGender\Gender::MONTENEGROGender\Gender::SERBIAGender\Gender::SLOVENIAGender\Gender::ALBANIAGender\Gender::GREECEGender\Gender::RUSSIAGender\Gender::BELARUSGender\Gender::MOLDOVAGender\Gender::UKRAINEGender\Gender::ARMENIAGender\Gender::AZERBAIJANGender\Gender::GEORGIAGender\Gender::KAZAKH_UZBEKGender\Gender::TURKEYGender\Gender::ARABIAGender\Gender::ISRAELGender\Gender::CHINAGender\Gender::INDIAGender\Gender::JAPANGender\Gender::KOREA(PECL gender >= 0.6.0)
Gender\Gender::connect — Connect to an external name dictionary
$dsn
) : boolConnect to an external name dictionary. Currently only streams are supported.
dsnDSN to open.
Boolean as success of failure.
(PECL gender >= 0.6.0)
Gender\Gender::__construct — Construct the Gender object
$dsn
] )Create a Gender object optionally connecting to an external name dictionary. When no external database was given, compiled in data will be used.
dsnDSN to open.
(PECL gender >= 0.8.0)
Gender\Gender::country — Get textual country representation
$country
) : arrayReturns the textual representation of a country from a Gender class constant.
countryA country ID specified by a Gender\Gender class constant.
Returns an array with the short and full names of the country on success
or FALSE on failure.
Example #1 Using Gender\Gender::country()
$gender = new Gender\Gender;
var_dump($gender->country(Gender\Gender::BRITAIN));
The above example will output:
array(2) {
'country_short' =>
string(2) "UK"
'country' =>
string(13) "Great Britain"
}
(PECL gender >= 0.6.0)
Gender\Gender::get — Get gender of a name
$name
[, int $country
] ) : intGet the gender of the name in a particular country.
nameName to check.
countryCountry id identified by Gender class constant.
Returns gender of the name.
(PECL gender >= 0.9.0)
Gender\Gender::isNick — Check if the name0 is an alias of the name1
$name0
, string $name1
[, int $country
] ) : arrayCheck whether the name0 is a nick of the name1.
name0Name to check.
name1Name to check.
countryCountry id identified by Gender class constant. If ommited ANY_COUNTRY is used.
Returns TRUE on success or FALSE on failure.
(PECL gender >= 0.9.0)
Gender\Gender::similarNames — Get similar names
$name
[, int $country
] ) : arrayGet similar names for the given name and country.
nameName to check.
countryCountry id identified by Gender class constant. If ommited ANY_COUNTRY is used.
Returns an array with the similar names found.
The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at » http://www.gnu.org/software/gettext/manual/gettext.html.
To use these functions you must download and install the GNU gettext package from » http://www.gnu.org/software/gettext/gettext.html
To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
This extension has no constants defined.
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
$domain
, string $codeset
) : string
With bind_textdomain_codeset(), you can set in which
encoding will be messages from domain returned by
gettext() and similar functions.
domainThe domain
codesetThe code set
A string on success.
(PHP 4, PHP 5, PHP 7)
bindtextdomain — Sets the path for a domain
$domain
, string $directory
) : stringThe bindtextdomain() function sets the path for a domain.
domainThe domain
directoryThe directory path
The full pathname for the domain currently being set.
Example #1 bindtextdomain() example
<?php
$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');
?>
The above example will output:
/usr/share/myapp/locale
(PHP 4, PHP 5, PHP 7)
dcgettext — Overrides the domain for a single lookup
$domain
, string $message
, int $category
) : stringThis function allows you to override the current domain for a single message lookup.
domainThe domain
messageThe message
categoryThe category
A string on success.
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
dcngettext — Plural version of dcgettext
$domain
, string $msgid1
, string $msgid2
, int $n
, int $category
) : stringThis function allows you to override the current domain for a single plural message lookup.
domainThe domain
msgid1
msgid2
n
category
A string on success.
(PHP 4, PHP 5, PHP 7)
dgettext — Override the current domain
$domain
, string $message
) : string
The dgettext() function allows you to override
the current domain for a single message lookup.
domainThe domain
messageThe message
A string on success.
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
dngettext — Plural version of dgettext
$domain
, string $msgid1
, string $msgid2
, int $n
) : string
The dngettext() function allows you to override
the current domain for a single plural message lookup.
domainThe domain
msgid1
msgid2
n
A string on success.
(PHP 4, PHP 5, PHP 7)
gettext — Lookup a message in the current domain
$message
) : stringLooks up a message in the current domain.
messageThe message being translated.
Returns a translated string if one is found in the translation table, or the submitted message if not found.
Example #1 gettext()-check
<?php
// Set language to German
putenv('LC_ALL=de_DE');
setlocale(LC_ALL, 'de_DE');
// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");
// Choose domain
textdomain("myPHPApp");
// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now
// Print a test message
echo gettext("Welcome to My PHP Application");
// Or use the alias _() for gettext()
echo _("Have a nice day");
?>
Note:
You may use the underscore character '_' as an alias to this function.
Note:
Setting a language isn't enough for some systems and the putenv() should be used to define the current locale.
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
ngettext — Plural version of gettext
$msgid1
, string $msgid2
, int $n
) : stringThe plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.
msgid1The singular message ID.
msgid2The plural message ID.
nThe number (e.g. item count) to determine the translation for the respective grammatical number.
Returns correct plural form of message identified by
msgid1 and msgid2
for count n.
Example #1 ngettext() example
<?php
setlocale(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken
?>
(PHP 4, PHP 5, PHP 7)
textdomain — Sets the default domain
$text_domain = NULL
) : stringThis function sets the domain to search within when calls are made to gettext(), usually the named after an application.
text_domain
The new message domain, or NULL to get the current setting without
changing it
If successful, this function returns the current message domain, after possibly changing it.
This module contains an interface to iconv character set conversion facility. With this module, you can turn a string represented by a local character set into the one represented by another character set, which may be the Unicode character set. Supported character sets depend on the iconv implementation of your system. Note that the iconv function on some systems may not work as you expect. In such case, it'd be a good idea to install the » GNU libiconv library. It will most likely end up with more consistent results.
This extension comes with various utility functions that help you to write multilingual scripts. Let's have a look at the following sections to explore the new features.
You will need nothing if the system you are using is one of the recent POSIX-compliant systems because standard C libraries that are supplied in them must provide iconv facility. Otherwise, you have to get the » libiconv library installed in your system.
This extension is enabled by default, although it may be disabled by compiling with --without-iconv.
The optional --with-iconv[=DIR] directive is used to specify the location of iconv on the system that PHP is being compiled on, otherwise only the default locations are scanned.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| iconv.input_encoding | "" | PHP_INI_ALL | Deprecated in PHP 5.6.0. |
| iconv.output_encoding | "" | PHP_INI_ALL | Deprecated in PHP 5.6.0. |
| iconv.internal_encoding | "" | PHP_INI_ALL | Deprecated in PHP 5.6.0. |
Here's a short explanation of the configuration directives.
Some systems (like IBM AIX) use "ISO8859-1" instead of "ISO-8859-1" so this value has to be used in configuration options and function parameters.
iconv.input_encoding
string
This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.
PHP 5.6 and later users should leave this empty and set
default_charset
instead.
iconv.output_encoding
string
This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.
PHP 5.6 and later users should leave this empty and set
default_charset
instead.
iconv.internal_encoding
string
This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.
PHP 5.6 and later users should leave this empty and set
default_charset
instead.
This extension has no resource types defined.
It is possible to identify at
runtime which iconv implementation is adopted by this extension.
| Name | Type | Description |
|---|---|---|
ICONV_IMPL |
string | The implementation name |
ICONV_VERSION |
string | The implementation version |
Note:
Writing implementation-dependent scripts with these constants is strongly discouraged.
The following constants are also available:
| Name | Type | Description |
|---|---|---|
ICONV_MIME_DECODE_STRICT |
integer | A bitmask used for iconv_mime_decode() |
ICONV_MIME_DECODE_CONTINUE_ON_ERROR |
integer | A bitmask used for iconv_mime_decode() |
See also GNU Recode functions.
(PHP 4 >= 4.0.5, PHP 5, PHP 7)
iconv_get_encoding — Retrieve internal configuration variables of iconv extension
Retrieve internal configuration variables of iconv extension.
type
The value of the optional type can be:
Returns the current value of the internal configuration variable if
successful or FALSE on failure.
If type is omitted or set to "all",
iconv_get_encoding() returns an array that
stores all these variables.
Example #1 iconv_get_encoding() example
<pre>
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
</pre>
The above example will output:
Array
(
[input_encoding] => ISO-8859-1
[output_encoding] => ISO-8859-1
[internal_encoding] => UTF-8
)
(PHP 5, PHP 7)
iconv_mime_decode_headers — Decodes multiple MIME header fields at once
$encoded_headers
[, int $mode = 0
[, string $charset = ini_get("iconv.internal_encoding")
]] ) : array
Decodes multiple MIME header fields at once.
encoded_headersThe encoded headers, as a string.
mode
mode determines the behaviour in the event
iconv_mime_decode_headers() encounters a malformed
MIME header field. You can specify any combination
of the following bitmasks.
| Value | Constant | Description |
|---|---|---|
| 1 | ICONV_MIME_DECODE_STRICT |
If set, the given header is decoded in full conformance with the
standards defined in » RFC2047.
This option is disabled by default because there are a lot of
broken mail user agents that don't follow the specification and don't
produce correct MIME headers.
|
| 2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header. |
charset
The optional charset parameter specifies the
character set to represent the result by. If omitted,
iconv.internal_encoding
will be used.
Returns an associative array that holds a whole set of
MIME header fields specified by
encoded_headers on success, or FALSE
if an error occurs during the decoding.
Each key of the return value represents an individual field name and the corresponding element represents a field value. If more than one field of the same name are present, iconv_mime_decode_headers() automatically incorporates them into a numerically indexed array in the order of occurrence.
Example #1 iconv_mime_decode_headers() example
<?php
$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
with SMTP id example for <example@example.com>;
Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
(envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
EOF;
$headers = iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");
print_r($headers);
?>
The above example will output:
Array
(
[Subject] => Prüfung Prüfung
[To] => example@example.com
[Date] => Thu, 1 Jan 1970 00:00:00 +0000
[Message-Id] => <example@example.com>
[Received] => Array
(
[0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id example for <example@example.com>; Thu, 1 Jan 1970 00:00:00 +0000 (UTC) (envelope-from example-return-0000-example=example.com@example.com)
[1] => (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
)
)
(PHP 5, PHP 7)
iconv_mime_decode — Decodes a MIME header field
$encoded_header
[, int $mode = 0
[, string $charset = ini_get("iconv.internal_encoding")
]] ) : string
Decodes a MIME header field.
encoded_headerThe encoded header, as a string.
mode
mode determines the behaviour in the event
iconv_mime_decode() encounters a malformed
MIME header field. You can specify any combination
of the following bitmasks.
| Value | Constant | Description |
|---|---|---|
| 1 | ICONV_MIME_DECODE_STRICT |
If set, the given header is decoded in full conformance with the
standards defined in » RFC2047.
This option is disabled by default because there are a lot of
broken mail user agents that don't follow the specification and don't
produce correct MIME headers.
|
| 2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header. |
charset
The optional charset parameter specifies the
character set to represent the result by. If omitted,
iconv.internal_encoding
will be used.
Returns a decoded MIME field on success,
or FALSE if an error occurs during the decoding.
Example #1 iconv_mime_decode() example
<?php
// This yields "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
0, "ISO-8859-1");
?>
(PHP 5, PHP 7)
iconv_mime_encode — Composes a MIME header field
$field_name
, string $field_value
[, array $preferences = NULL
] ) : string
Composes and returns a string that represents a valid MIME
header field, which looks like the following:
Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile
field_nameThe field name.
field_valueThe field value.
preferences
You can control the behaviour of iconv_mime_encode()
by specifying an associative array that contains configuration items
to the optional third parameter preferences.
The items supported by iconv_mime_encode() are
listed below. Note that item names are treated case-sensitive.
| Item | Type | Description | Default value | Example |
|---|---|---|---|---|
| scheme | string |
Specifies the method to encode a field value by. The value of
this item may be either "B" or "Q", where "B" stands for
base64 encoding scheme and "Q" stands for
quoted-printable encoding scheme.
|
B | B |
| input-charset | string |
Specifies the character set in which the first parameter
field_name and the second parameter
field_value are presented. If not given,
iconv_mime_encode() assumes those parameters
are presented to it in the
iconv.internal_encoding
ini setting.
|
iconv.internal_encoding | ISO-8859-1 |
| output-charset | string |
Specifies the character set to use to compose the
MIME header.
|
iconv.internal_encoding | UTF-8 |
| line-length | integer | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to » RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. | 76 | 996 |
| line-break-chars | string |
Specifies the sequence of characters to append to each line
as an end-of-line sign when "folding" is performed on a long header
field. If not given, this defaults to "\r\n"
(CR LF). Note that
this parameter is always treated as an ASCII string regardless
of the value of input-charset.
|
\r\n | \n |
Returns an encoded MIME field on success,
or FALSE if an error occurs during the encoding.
Example #1 iconv_mime_encode() example
<?php
$preferences = array(
"input-charset" => "ISO-8859-1",
"output-charset" => "UTF-8",
"line-length" => 76,
"line-break-chars" => "\n"
);
$preferences["scheme"] = "Q";
// This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung=20Pr=C3=BCfung?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
$preferences["scheme"] = "B";
// This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
?>
(PHP 4 >= 4.0.5, PHP 5, PHP 7)
iconv_set_encoding — Set current setting for character encoding conversion
$type
, string $charset
) : bool
Changes the value of the internal configuration variable specified by
type to charset.
type
The value of type can be any one of these:
charsetThe character set.
Returns TRUE on success or FALSE on failure.
Example #1 iconv_set_encoding() example
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
?>
(PHP 5, PHP 7)
iconv_strlen — Returns the character count of string
$str
[, string $charset = ini_get("iconv.internal_encoding")
] ) : int
In contrast to strlen(),
iconv_strlen() counts the occurrences of characters
in the given byte sequence str on the basis of
the specified character set, the result of which is not necessarily
identical to the length of the string in byte.
strThe string.
charset
If charset parameter is omitted,
str is assumed to be encoded in
iconv.internal_encoding.
Returns the character count of str, as an integer.
(PHP 5, PHP 7)
iconv_strpos — Finds position of first occurrence of a needle within a haystack
$haystack
, string $needle
[, int $offset = 0
[, string $charset = ini_get("iconv.internal_encoding")
]] ) : int
Finds position of first occurrence of a needle
within a haystack.
In contrast to strpos(), the return value of
iconv_strpos() is the number of characters that
appear before the needle, rather than the offset in bytes to the
position where the needle has been found. The characters are counted
on the basis of the specified character set charset.
haystackThe entire string.
needleThe searched substring.
offset
The optional offset parameter specifies
the position from which the search should be performed.
If the offset is negative, it is counted from the end of the string.
charset
If charset parameter is omitted,
string are assumed to be encoded in
iconv.internal_encoding.
If haystack or needle is
not a string, it is converted to a string and applied as the ordinal
value of a character.
Returns the numeric position of the first occurrence of
needle in haystack.
If needle is not found,
iconv_strpos() will return FALSE.
This function may
return Boolean FALSE, but may also return a non-Boolean value which
evaluates to FALSE. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
| Version | Description |
|---|---|
| 7.1.0 |
Support for negative offsets has been added.
|
(PHP 5, PHP 7)
iconv_strrpos — Finds the last occurrence of a needle within a haystack
$haystack
, string $needle
[, string $charset = ini_get("iconv.internal_encoding")
] ) : int
Finds the last occurrence of a needle
within a haystack.
In contrast to strrpos(), the return value of
iconv_strrpos() is the number of characters that
appear before the needle, rather than the offset in bytes to the
position where the needle has been found. The characters are counted
on the basis of the specified character set charset.
haystackThe entire string.
needleThe searched substring.
charset
If charset parameter is omitted,
string are assumed to be encoded in
iconv.internal_encoding.
If haystack or needle is
not a string, it is converted to a string and applied as the ordinal
value of a character.
Returns the numeric position of the last occurrence of
needle in haystack.
If needle is not found,
iconv_strrpos() will return FALSE.
This function may
return Boolean FALSE, but may also return a non-Boolean value which
evaluates to FALSE. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.
(PHP 5, PHP 7)
iconv_substr — Cut out part of a string
$str
, int $offset
[, int $length = iconv_strlen($str, $charset)
[, string $charset = ini_get("iconv.internal_encoding")
]] ) : string
Cuts a portion of str specified by the
offset and length parameters.
strThe original string.
offset
If offset is non-negative,
iconv_substr() cuts the portion out of
str beginning at offset'th
character, counting from zero.
If offset is negative,
iconv_substr() cuts out the portion beginning
at the position, offset characters
away from the end of str.
length
If length is given and is positive, the return
value will contain at most length characters
of the portion that begins at offset
(depending on the length of string).
If negative length is passed,
iconv_substr() cuts the portion out of
str from the offset'th
character up to the character that is
length characters away from the end of the string.
In case offset is also negative, the start position
is calculated beforehand according to the rule explained above.
charset
If charset parameter is omitted,
string are assumed to be encoded in
iconv.internal_encoding.
Note that offset and length
parameters are always deemed to represent offsets that are
calculated on the basis of the character set determined by
charset, whilst the counterpart
substr() always takes these for byte offsets.
Returns the portion of str specified by the
offset and length parameters.
If str is shorter than offset
characters long, FALSE will be returned.
If str is exactly offset
characters long, an empty string will be returned.
| Version | Description |
|---|---|
| 7.0.11 |
If str is equal to
offset characters long, an empty string will be
returned. Prior to this version, FALSE was returned in this case.
|
(PHP 4 >= 4.0.5, PHP 5, PHP 7)
iconv — Convert string to requested character encoding
$in_charset
, string $out_charset
, string $str
) : string
Performs a character set conversion on the string
str from in_charset
to out_charset.
in_charsetThe input charset.
out_charsetThe output charset.
If you append the string //TRANSLIT to
out_charset transliteration is activated. This
means that when a character can't be represented in the target charset,
it can be approximated through one or several similarly looking
characters. If you append the string //IGNORE,
characters that cannot be represented in the target charset are silently
discarded. Otherwise, E_NOTICE is generated and the function
will return FALSE.
If and how //TRANSLIT works exactly depends on the
system's iconv() implementation (cf. ICONV_IMPL).
Some implementations are known to ignore //TRANSLIT,
so the conversion is likely to fail for characters which are illegal for
the out_charset.
strThe string to be converted.
Returns the converted string or FALSE on failure.
| Version | Description |
|---|---|
| 5.4.0 |
Since this version, the function returns FALSE on illegal characters,
unless //IGNORE is specified in output charset.
Before, it returned partial output string.
|
Example #1 iconv() example
<?php
$text = "This is the Euro symbol '€'.";
echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
echo 'Plain : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;
?>
The above example will output something similar to:
Original : This is the Euro symbol '€'. TRANSLIT : This is the Euro symbol 'EUR'. IGNORE : This is the Euro symbol ''. Plain : Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7
(PHP 4 >= 4.0.5, PHP 5, PHP 7)
ob_iconv_handler — Convert character encoding as output buffer handler
$contents
, int $status
) : string
Converts the string encoded in internal_encoding to
output_encoding.
internal_encoding and
output_encoding should be defined in the php.ini
file or in iconv_set_encoding().
See ob_start() for information about this handler parameters.
See ob_start() for information about this handler return values.
Example #1 ob_iconv_handler() example:
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
ob_start("ob_iconv_handler"); // start output buffering
?>
Internationalization extension (further is referred as Intl) is a wrapper for » ICU library, enabling PHP programmers to perform various locale-aware operations including but not limited to formatting, transliteration, encoding conversion, calendar operations, » UCA-conformant collation, locating text boundaries and working with locale identifiers, timezones and graphemes,
It tends to closely follow ICU APIs, so that people having experience working with ICU in either C/C++ or Java could easily use the PHP API. Also, this way ICU documentation would be useful to understand various ICU functions.
Intl consists of several modules, each of them exposes the corresponding ICU API:
To build the extension you need to install the » ICU library, version 4.0.0 or newer is required. As of PHP 7.4.0 ICU 50.1 or newer is required.
This extension is bundled with PHP as of PHP version 5.3.0. Alternatively, the PECL version of this extension may be used with all PHP versions greater than 5.2.0 (5.2.4+ recommended).
This extension may be installed using the bundled version as of PHP 5.3.0, or as a PECL extension as of PHP 5.2.0. In other words, there are two methods to install the intl extension.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/intl.
Alternatively, --enable-intl will enable the bundled
version while compiling PHP.
If your ICU is installed to a non-standard directory then you might want to
specify its location in
LD_LIBRARY_PATH
environment variable so that dynamic linker can find it:
Otherwise, if PHP and ICU are installed to their default locations, then the additional options to `configure' are not needed.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| intl.default_locale | PHP_INI_ALL | ||
| intl.error_level | 0 | PHP_INI_ALL | |
| intl.use_exceptions | 0 | PHP_INI_ALL | Available since PHP 5.5 and PECL 3.0.0a1 |
Here's a short explanation of the configuration directives.
intl.default_locale
string
The locale that will be used in intl functions when none is specified
(either by omitting the corresponding argument or by passing
NULL). These are ICU locales, not system locales.
The built-in ICU locales and their data can be explored at
» http://demo.icu-project.org/icu-bin/locexp.
The default value is empty, which forces the usage of ICU's default locale. Once set, the ini setting cannot be reset to this default value. It is not recommended that this default be relied on, as its effective value depends on the server's environment.
intl.error_level
integer
The level of the error messages generated when an error occurs in ICU
functions. This is a PHP error level, such as
E_WARNING. It can be set to 0
in order to inhibit the messages. This does not affect the return values
indicating error or the values returned by
intl_get_error_code() or by the class specific
methods for retrieving error codes and messages.
Choosing E_ERROR will terminate the script whenever
an error condition is found on intl classes.
The default value is 0.
intl.use_exceptions
integer
If set to true, an exception will be raised whenever an error occurs in an intl function. The exception will be of type IntlException. This is possibly in addition to the error message generated due to intl.error_level.
The default value is FALSE.
This extension has no resource types defined.